Kiran Mohan
Kiran Mohan

Reputation: 3006

how to load a java class along with static initializations before they are used?

I need to load some classes along with their respective static initializations, for example, in a factory method implementation.

If I just make reference to the class using the below syntax, the JVM does not run the static initialization part. Actually, does the JVM even load the classes?

Class<Shape> shapeClass = Shape.class;
or
Shape s = null;

But with class.forname() it does execute static initializations. Class.forname("Shape"); The question is if this is the only way to do load a java class along with static initializations? Or are there other ways? Any significant performance penalties for using class.forname()?

Upvotes: 2

Views: 118

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

From Class.forName(String className) API: Invoking this method is equivalent to: Class.forName(className, true, currentLoader).

The second argument = true means initialize class, and initialize class means run static initializers

This is a test to check

package test;

class Test2 {
    static {
        System.out.println("static init");
    }
}

public class Test1 {

    public static void main(String[] args) throws Exception {
        Class.forName("test.Test2");
    }
}

output

static init

but if you load Test2 with

Class.forName("test.Test2", false, ClassLoader.getSystemClassLoader());

there will be no output. You can also use this test to see that Test.class.getName() does not load the class either.

The simplest way to make it load is to add an empty static method and call it:

class Test2 {
     public static void load() {
     }
     ...
Test2.load();

Upvotes: 3

NilsH
NilsH

Reputation: 13821

When you load/resolve a class, the static initializers are executed in the order they are defined. It shouldn't matter how you load them, reflection or not. That is, unless you're meaning some other sort of initialization?

Upvotes: 1

Related Questions