[antlr-interest] [OT] Static initialization in Java (was: Re: site back up)

Dennis Benzinger Dennis.Benzinger at gmx.net
Tue Aug 26 12:19:21 PDT 2008


Am 26.08.2008 20:33, Randall R Schulz schrieb:
> On Tuesday 26 August 2008 11:27, Dennis Benzinger wrote:
>> Hi!
>>
>> ...
>>
>> Static initializers are executed when the class is initialized. See
>> http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.
>>7
>>
>> When a class is initialized is described in detail in
>> http://java.sun.com/docs/books/jls/third_edition/html/execution.html#
>>12.4.1
>>
>> Simply referring to HomePage.class will not initialize the class.
> 
> That really depends on what you mean by "refer[ing] to." That value does 
> not exist unless and until the class is loaded, after all.

I didn't find anything definitive about that in the language
specification but I think because HomePage.class is an instance of class
Class<HomePage> (or just Class before Java 5) it only requires the
initialization of class Class. Initialization of class HomePage is not
required.

> I don't 
> believe it's possible to load a class that contains any compiled 
> reference to a class literal in this form that does not trigger loading 
> of the class in question.
> [...]

It's possible. Try:

class StaticTestClass {
    static {
        System.out.println("Static initializer of StaticTestClass");
    }
}

class Test {
    public static void main(String[] args) {
        System.out.println(StaticTestClass.class.getName());
    }
}

Only some methods of class Class<E> require the initialization of class E.

Dennis Benzinger


More information about the antlr-interest mailing list