I got a question about Enum.
I have an enum class looks like below
public enum FontStyle {
NORMAL(\"This font has normal style.\"),
BOLD(\"T
Enum instances are created during class linking (resolution), which is a stage that comes after class loading, just like static fields of a "normal" class.
Class linking happens separately from class loading. So if you dynamically load the Enum class using a class loader, the constants will be instantiated only when you actually try to access one of the instances, for example, when using the method getEnumConstants()
from Class
.
Here is a bit of code to test the above assertion:
File1: TestEnum.java
public enum TestEnum {
CONST1, CONST2, CONST3;
TestEnum() {
System.out.println( "Initializing a constant" );
}
}
File2: Test.java
class Test
{
public static void main( String[] args ) {
ClassLoader cl = ClassLoader.getSystemClassLoader();
try {
Class> cls = cl.loadClass( "TestEnum" );
System.out.println( "I have just loaded TestEnum" );
Thread.sleep(3000);
System.out.println( "About to access constants" );
cls.getEnumConstants();
} catch ( Exception e ) {
e.printStackTrace();
System.exit(1);
}
}
}
The output:
I have just loaded TestEnum... three seconds pause ...
About to access constants Initializing a constant Initializing a constant Initializing a constant
The distinction is important if, for any reason, you are not using the enum plainly (just by referring to one of its constants) but instead rely on dynamically loading it.
Notes:
Class.forName()
will both load and link the class, so the constants will be immediately instantiated.