Assertions in static blocks ?
David Holmes - Sun Microsystems
David.Holmes at Sun.COM
Mon Mar 8 14:48:30 PST 2010
Ulf Zibis said the following on 03/08/10 22:40:
> Am 07.03.2010 23:20, schrieb David Holmes - Sun Microsystems:
>> Ulf Zibis said the following on 03/08/10 01:40:
>>> In contrast to Keith and Neal, I think, we agree, that this
>>> "behaviour is surprising", so I would vote at least for a *warning*
>>> from javac side.
>>
>> I'm with Keith and Neal, this is all "working as designed". How can
>> javac in general know whether or not a class will be initialized.
>
> This is not the question here. The question is if it *can* be
> initialized, (1) via standard java instruction or (2) via any other
> special magic like reflective call from Class.forName(). javac surely
> has knowledge about that.
Both (1) and (2) depend on your whole program not the class being
compiled. So javac can not know the answer to this at compile time.
> If (1) could never be reached, there should be a warning, in particular
> for less experienced programmers, E.g.:
> "static initializer will never be triggered by any member or method of
> this class. Could only be invoked by loading the class explicitly or
> inherently(not sure)"
No that doesn't make sense. A classes own methods/members are not the
trigger for classloading and/or initialization. It is the use of those
methods/members by other classes that triggers the
loading/initialization of the class containing the method/member.
>> A static initializer is no different to a method or constructor in
>> that regard: none of them are ever flagged as unreachable because that
>> can't be determined a-priori by javac.
>
> IMHO there is a _big_ difference on normal constructors and methods:
> 1. They _can_ always be executed by normal java instruction.
> 2. They will _never_ be executed, if not explicitly called from code.
> On static initializers it's quite different:
> 1. They _cannot_ be executed by normal java instruction.
> 2. They will _mostly_ be _automatically_ executed but not ever, if a
> member/method from it's class is called
The implicit vs explicit nature of the execution doesn't change the fact
that to determine if either is executed you need to look at the whole
program - not just the class(es) being compiled.
David Holmes
>
>>
>> At the absolute most I can concede that javac might issue a warning if
>> a class consisted only of constant field declarations and had a static
>> initializer, as no use of the fields would lead to initialization. But
>> even then I don't think this is worth the effort.
>
> From my point of view, warnings about "unchecked conversion" are often
> not worth the effort. I can't imagine any case, what could become
> broken, if ignored here:
> List<MyClass> list = new ArrayList();
>
>
> -Ulf
>
More information about the compiler-dev
mailing list