开发者

Create a proxy class with a no-arg constructor

开发者 https://www.devze.com 2023-04-03 16:32 出处:网络
Using a java.lang.reflect.Proxy, I can create a class that takes an InvocationHandler as constructor argument. However, the cl开发者_如何学Cass will be instantiated via newInstance() somewhere in the

Using a java.lang.reflect.Proxy, I can create a class that takes an InvocationHandler as constructor argument. However, the cl开发者_如何学Cass will be instantiated via newInstance() somewhere in the framework, and the InvocationHandler can be the same for all instances.

Can I add a no-arg constructor to the proxy class, which passes my InvocationHandler to the original constructor?


I'm afraid it won't work hat way, as the actual proxy magic happens in this native code

private static native Class defineClass0(ClassLoader loader, String name,
                     byte[] b, int off, int len);

that's only accessed through the static Method Proxy.newProxyInstance(ClassLoader, Class<?>[], InvocationHandler). This method in turn calls the constructor of the thusly generated class with the supplied InvocationHandler as parameter.

So there's no way for you to return a Proxy from a newInstance() call. The closest you can get is to instantiate the InvocationHandler with newInstance() and pass it to the static factory method.

Or you could take the whole thing one step further, have a Class that implements he target interface(s), constructs a proxy field through the factory method and delegates all interface methods to the Proxy. But that would be a proxy around a proxy, and I really don't see the point of that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号