How is it possible to know whether a class has been initialized?
Class cl = Class.forName("com.example.MyClass", false, getClass().getClassLoader());
// the false argument above indicates that the class should not be initialized
// but how can I check whether it already was?
cl.isInitialized(); // this does not exist, how can I know instead?
About why I want to know that:
On a client's project, we have an ugly class(*) with lots of static members which I want to test. For the test to be predictable, the static members must have their default values, which are set on initializing. If the JUnit testing starts a new JVM for each test class, this is not a problem: the class is freshly loaded on each execution. But when I execute the tests in Eclipse along with others, the same JVM is used for several tests and the class is not freshly loaded and the members don't have their default values anymore. I want to be able to decide, whether the test makes sense (because the class will be freshly loaded) or if I should just return because the test makes not sense if the static members have been modified.
(*) refactoring is scheduled, but not just for right now
Simplified version of the class
public class Settings {
public static Properties props;
static{
props.setProperty("key1", "val1");
props.setProperty("key2", "val2");
}
}
And the test class
public class SettingsTest extends TestCase {
public void testDefauts() throws Exception {
Class cl = Class.forName("Settings", false, getClass().getClassLoader());
if(cl.isInitialized){ // doesn't exist
// Cannot test default values, because class was already initialized
return;
}
Properties props = Settings.props; // Settings is initialized here
assertEquals("val1", props.getProperty("key1"));
assertEquals("val2", props.getProperty("key2"));
}
}