Discussions

General J2EE: How to instantiate a singleton class using reflection

  1. I have a singleton class, MySingleton.java in package x

    I want to instantiate this singleton class using Reflection from another class which is in a different package, say package y;

    How to achieve this.


    Thanks,


    -Ram
  2. If your class has a no-parameter constructor, it is pretty easy to create an object using the Class class:

    String className = // fully qualified class name
    Object o = Class.forName(className).newInstance();

    You can specify the class name in a configuration file.
  3. My class is a singleton class and the constructor is private/protected.

    I cannot access private/protected constructors from outside of the class inorder to create instance of the class,I can only do it by calling the public static getInstance() method.


    if I do this : Object o = Class.forName(className).newInstance(), I will get an IllegalAccessException.

    -Ram
  4. If you know that the getInstance() method will always have that name, you can use reflection on that method:

    Class cls = Class.forName(className);
    Method method = cls.getMethod("getInstance", new Class[0]);
    Object o = method.invoke(null, new Object[0]);

    The null parameter is legal for the invoke() method, provided that the method is static.
  5. Thanks a lot.

    I did it similiar to what you said, instead of passing null to invoke method, i just passed class object, in this case cls

    Class cls = Class.forName(className);
    Method method = cls.getMethod("getInstance", new Class[0]);
    Object o = method.invoke(cls, new Object[0]);



    -Ram