• Post Reply Bookmark Topic Watch Topic
  • New Topic

Singleton and Reflection  RSS feed

 
Souvik Dasgupta
Ranch Hand
Posts: 98
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hello folks,

I have a query regarding Java Reflection.

I have a Class that is a Singleton.Now can I invoke a method on it using Java Reflection?If Yes, how? For your information, both of my classes occur in same package.But it may not be the case always.

Help will be very much appreciated.

I am showing my sample classes below:

Singleton.java



UseReflect.java



 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The call to newInstance() is going to throw an exception since it tries to call the public constructor without parameters. There is no such constructor though.

There are two ways to get an instance:
1) get the right Constructor from the class, call setAccessible(true) on it and use the Constructor to create the instance.
2) get the getInstance() method and invoke it with null (because it's a static method) as the first argument.

I would definitely go for option 2. Option 1 causes your singleton to no longer be a singleton, as there can be multiple instances. Also, the security manager can disallow calling setAccessible(true) on the private constructor. Option 2 will always work (as long as the method is there).


Oh, and don't call toString() on the return value of the invoke method. Since it's a void method the return value will always be null, and you'll get a NullPointerException. Simply call "System.out.println(method.invoke(obj));" - the println will turn the result into a String all by itself.
 
Souvik Dasgupta
Ranch Hand
Posts: 98
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Thanks a lot Rob.

This is exactly what I was looking for.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!