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
-
How to instantiate a singleton class using reflection (4 messages)
- Posted by: Ramesh Mandapati
- Posted on: April 22 2004 14:24 EDT
Threaded Messages (4)
- How to instantiate a singleton class using reflection by Paul Strack on April 22 2004 16:28 EDT
- How to instantiate a singleton class using reflection by Ramesh Mandapati on April 22 2004 16:49 EDT
-
How to instantiate a singleton class using reflection by Paul Strack on April 22 2004 08:55 EDT
- How to instantiate a singleton class using reflection by Ramesh Mandapati on April 23 2004 01:28 EDT
-
How to instantiate a singleton class using reflection by Paul Strack on April 22 2004 08:55 EDT
- How to instantiate a singleton class using reflection by Ramesh Mandapati on April 22 2004 16:49 EDT
-
How to instantiate a singleton class using reflection[ Go to top ]
- Posted by: Paul Strack
- Posted on: April 22 2004 16:28 EDT
- in response to Ramesh Mandapati
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. -
How to instantiate a singleton class using reflection[ Go to top ]
- Posted by: Ramesh Mandapati
- Posted on: April 22 2004 16:49 EDT
- in response to Paul Strack
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 -
How to instantiate a singleton class using reflection[ Go to top ]
- Posted by: Paul Strack
- Posted on: April 22 2004 20:55 EDT
- in response to Ramesh Mandapati
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. -
How to instantiate a singleton class using reflection[ Go to top ]
- Posted by: Ramesh Mandapati
- Posted on: April 23 2004 13:28 EDT
- in response to Paul Strack
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