0

Assume, I load the class by the ClassLoader at the runtime:

Class<MyInterface> clazz = (Class<MyInterface>)getClass().getClassLoader().loadClass("ImplementerOfMyInterface");

The new instance I can create then by

MyInterface myInt = clazz.newInstance();

But when I need to get the instance of the singleton by its name that implements the MyInterface instead of creating the new one, what should be done?

1
  • Fields have names, but Instances don't have names. Can you give an example of what you mean? Commented Jun 15, 2012 at 11:25

1 Answer 1

3

Instead of invoking newInstance, you could invoke a static "getInstance" method (or whatever singleton getter method name you use).

For example:

public class ReflectTest {

    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("ReflectTest");
        Method m = clazz.getDeclaredMethod("getInstance", null);
        Object o = m.invoke(null, null);
        System.out.println(o == INSTANCE);
    }

    public static ReflectTest getInstance() {
        return INSTANCE;
    }

    private static final ReflectTest INSTANCE = new ReflectTest();

    private ReflectTest() {
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.