next up previous contents
Next: Inner and Anonymous Classes Up: Other Topics Previous: Packaging   Contents

Class Initialization

What is the relationship of reflection with class initialization? That is, there are rules having to do with ``active use'' and class initialization upon loading a new class. When using Class.forName(...) to load a previous unloaded class or when invoking reflective methods on a Class class, when does initialization occur, if at all?

Given a Class class representing some underlying class, the reflective methods (eg. getFields()/get...()) do not cause class initialization if the underlying class is not already initialized. The Class.forName() method is overloaded: one version simply takes a class name and an alternate version takes the class name and a flag indicating whether to initialize the class or not. By default, the first version of Class.forName() calls the second with a true flag, thus causing class initialization.

It is possible that one uses ClassLoader::loadClass() to load a class which is not initialized. Then, calling the reflective methods on the resulting Class object will not constitute an ``active use.'' Previously, there was a bug in which the JDK implementation did not follow this specification and a call to Class::getFields() would cause an uninitialized class to be initialized. This was fixed in, bug report number #4084324, so that: ``Definitely reflection must NOT cause classes to be initialized.''
See http://developer.java.sun.com/developer/bugParade/.


next up previous contents
Next: Inner and Anonymous Classes Up: Other Topics Previous: Packaging   Contents
Nadeem Hamid 2000-07-24