Citation :
Virtual Machine - Previously, evaluating a class literal (for example, Foo.class) caused the class to be initialized; as of 5.0, it does not. Code that depends on the previous behavior should be rewritten. You can use the following code to force initialization of a class:
Code :
- //... Foo.class ... //OLD CODE
- ... forceInit(Foo.class) ... //NEW CODE
-
- /**
- * Forces the initialization of the class pertaining to
- * the specified <tt>Class</tt> object.
- * This method does nothing if the class is already
- * initialized prior to invocation.
- *
- * @param klass the class for which to force initialization
- * @return <tt>klass</tt>
-
- */
- public static <T> Class<T> forceInit(Class<T> klass) {
- try {
- Class.forName(klass.getName(), true, klass.getClassLoader());
- } catch (ClassNotFoundException e) {
- throw new AssertionError(e); // Can't happen
- }
- return klass;
- }
|
The new behavior is a consequence of the fact that the VM now supports class literals in the constant pool. The old behavior remains in classes compiled with a pre-5.0 compiler or with the -target 1.4 flag, even if run in the 5.0 VM. For more information, see Initialization of Classes and Interfaces (section 12.4) in The Java Language Specification. Note that the language specification hasn't changed; it never listed class literal evaluation as an initialization trigger.
|