Name: wl91122 Date: 07/21/99
The compiler might have a bug in code generation for anonymous
classes.
Non-local variables referenced in an anonymous subclass are
not copied before the base class constructor is called.
(This might not be a compiler bug but might be a flaw in
how inner classes are defined. That is, the language spec.
might define that non-local variables are defined to be copied
in during initialization of the anonymous subclass (instead of
before construction of the base class even starts). If
that's the case, then that definition should be reworked to
yield more intuitive (and useful) behavior.)
Here's my test case:
package test;
/*
Demonstrates possible code generation error in JDK 1.1.7B compiler.
It appears that non-local variables that are referenced in an anonymous
class are not properly copied (or otherwise made accessible) before the
base class constructor is called.
The output from the JDK 1.1.7B compiler is:
callingMethod.1: parameter = whatever
callingMethod.1: local_var = hello
calledByConstructor (constructor): parameter = null
calledByConstructor (constructor): local_var = null
<init>: parameter = whatever
<init>: local_var = hello
calledByConstructor (callingMethod): parameter = whatever
calledByConstructor (callingMethod): local_var = hello
callingMethod.2: parameter = whatever
callingMethod.2: local_var = hello
Note how variables "parameter" and "local_var" are seen as null
from the anonymous subclass at the time the base class constructor
is active.
*/
import java.util.Enumeration;
import java.util.Vector;
class Test
{
public static void main( String[] args )
{
callingMethod( "whatever" );
} // main();
protected static void callingMethod( final String parameter )
{
final String local_var = "hello";
System.err.println( "callingMethod.1: parameter = " + parameter );
System.err.println( "callingMethod.1: local_var = " + local_var );
BaseClass enum = new BaseClass()
{
{
System.err.println( "<init>: parameter = " + parameter );
System.err.println( "<init>: local_var = " + local_var );
//enum.calledByConstructor();
}
public void calledByConstructor( String caller )
{
System.err.println( "calledByConstructor (" + caller + "): parameter = " + parameter );
System.err.println( "calledByConstructor (" + caller + "): local_var = " + local_var );
}
};
enum.calledByConstructor( "callingMethod" );
System.err.println( "callingMethod.2: parameter = " + parameter );
System.err.println( "callingMethod.2: local_var = " + local_var );
} // callingMethod(...)
} // class Test
abstract class BaseClass
{
protected BaseClass()
{
calledByConstructor( "constructor" );
} // BaseClass()
protected abstract void calledByConstructor( String caller );
} // class BaseClass
DSB/DFI
(Review ID: 54104)
======================================================================