Java InvocationHandler and Singleton

I have a singleton object "MySingle", which in all classes I return as MySingle.createOrGetInstance();

Now the problem I am facing is that I would like to do some registration of methods and other things before calling the method in MySingle, so I looked at the Java class InvocationHandler Source Link

However, now the problem is how can I call the singleton method, because when I use the same code and instead of doing

 DebugProxy.newInstance(new FooImpl()); 

I'm doing it

DebugProxy.newInstance(MySingle.createOrGetInstance()); But when I do this, I get a Cast Cast expression when I finish assigning the result to the `(MySingle sing) variable.

Im developing on Android, but I doubt that matters :).

Thanks Faisal abid

0
source share
2 answers

For a normal java application (I don’t know android) it will fail because java.lang.reflect.Proxy will work only for interfaces!

A dynamic proxy class (simply called the proxy class below) is a class that implements a list of interfaces specified at runtime when creating the class, with the behavior described below.

@see: Java Proxy Document

In your case, DebugProxy from java reflection guid ( http://download.oracle.com/javase/1.3/docs/guide/reflection/proxy.html ) uses java.lang.reflect.Proxy!

There is a class in your MySingle code, but java.lang.reflect.Proxy only implements the interfaces of this class. Therefore, when creating java.lang.reflect.Proxy created for the MySingle class in the class , MySingle must fail the class exception because Proxy is not a subclass of MySingle .

One desktop that will work: it will introduce the MySingle interface and implement the MySingleImpl class (using the getInstance method), and then use the interface everywhere (except for creating).

+2
source

To debug Android applications, diff is used. calss, which is implemented specifically for android


see link

0
source

Source: https://habr.com/ru/post/1447818/


All Articles