Using a java.lang.reflect.Proxy, I can create a class that takes an InvocationHandler as constructor argument. However, the class 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
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 suppliedInvocationHandleras parameter.So there’s no way for you to return a Proxy from a
newInstance()call. The closest you can get is to instantiate theInvocationHandlerwithnewInstance()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.