Simon
Simon

Reputation: 11

Java: Store reference to static class is variable

I need to store a reference to a class in a variable, such that I can call the static methods of that class on the variable.

Main.java

public class Main {

    private static SomeClass cls;

    private static void main(String[] args) {
        **cls = SomeClass;**
        cls.doSomething();
    }

SomeClass.java

public class SomeClass() {
    public static doSomething() {
    }
}

cls = SomeClass is not working here, but I also don't want to instantiate SomeClass.

Can anyone help?

Upvotes: 1

Views: 2842

Answers (2)

rahul kale
rahul kale

Reputation: 11

You can use reflection for this requirement. Below is example:

public class Reference {

    public static Class clazz = null;

    public static void main(String[] args) {
        try {
            refer(Something.class);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void refer(Class clazzToBeCalled) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        clazz = clazzToBeCalled; //No need to store it on class level
        Method methodToBeCalled = clazz.getMethod("doSomething");
        methodToBeCalled.invoke(null);
    }
}

Upvotes: 0

Eran
Eran

Reputation: 393781

This makes no sense.

You can write

private static SomeClass cls = null;

(or leave it unassigned, since the default value would be null anyway)

and

cls.doSomething()

will not throw NullPointerException and will call the static method.

However, there's no reason to do it. Regardless of what you assign to the cls variable, it will always call SomeClass.doSomething(), so it would make more sense to eliminate that variable and simply call SomeClass.doSomething().

The idea is that cls can reference several classes based on some condition which is not provided in the code above

This idea won't work. The compile time type of the cls variable will determine the class of the static method being called. Since it can only have a single type, it will always be the same static method.

Upvotes: 4

Related Questions