A comment on Java style

Jim White jim@pagesmiths.com
Fri Dec 20 10:36:00 GMT 2002


Per Bothner wrote:
> Jim White wrote:
> 
>> Works if a static is needed too:
>>
>> final static String CLASSNAME = MyClass.class.getName();
> 
> The advantage is that the javac compiler fill in the package
> name, and gives you an error if it can't find the class.
> 
> The disadvantage is that the generated bytecode is (essentially):
>   Class.forName("MyClass").getName()
> This is slower, and takes up more space in the bytecode.
> Furthermore, it causes MyClass to be initialized.

Well, actually the MyClass.class generates a getstatic, and naturally 
the getName requires invokevirtual.  Certainly more overhead than the 
loadconstant for the literal string.  That (if the execution time was an 
issue) is why I pointed out that this can be used in a static 
initializer (although chances are a final variable around the inner loop 
would be just as good).

But as you say, referring to a class this way means that it must be 
loaded and initialized (which in the case of the static is when that 
would happen anyhow if it were within the same class).

So only the case where I needed to play with a class's name but not 
cause it to be initialized (a rarity for any ordinary application, but 
certainly can arise in language implementation level stuff) would I have 
to avoid this construct (and wouldn't be expecting any help from a 
refactoring tool or other reflective process anyhow).

jim



More information about the Kawa mailing list