Java InvocationHandler and a Singleton
I have a singleton object "MySingle" which all through my classes I retrevie as MySingle.createOrGetInstance();
Now the problem I am having i开发者_开发知识库s that I would like to do some Method Logging and other stuff before a method in MySingle is called, so I looked into the Java InvocationHandler class Source Link
However the problem is now how would I call the singleton method, because when I use the same code and instead of doing
DebugProxy.newInstance(new FooImpl());
I do this
DebugProxy.newInstance(MySingle.createOrGetInstance());
But when I do this, I get a class Cast expression when I end up assigning the result to a variable `(MySingle sing).
Im developing on Android but I doubt that makes any difference :).
Thanks, Faisal abid
For a normal java application (I don't know android) it will fail, because the java.lang.reflect.Proxy
will only work for interfaces!
A dynamic proxy class (simply referred to as a proxy class below) is a class that implements a list of interfaces specified at runtime when the class is created, with behavior as described below.
@see: Proxy Java Doc
In your case, the DebugProxy from the java reflection guid (http://download.oracle.com/javase/1.3/docs/guide/reflection/proxy.html), uses java.lang.reflect.Proxy!
In your code MySingle
is a class, but a java.lang.reflect.Proxy
only implement the Interfaces of this class. So casting a java.lang.reflect.Proxy
, created for the class MySingle
, to the class must MySingle
fail with an class cast exception, because the Proxy is not an subclass of MySingle
.
One workarround that would work: would be intoducing an Interface MySingle and implemement a class MySingleImpl (with the getInstance method), and then use everywhere (except creation) the interface.
For android application debug is diff. calss which is implemented for specially for android
see this link
精彩评论