Java – How to use a dynamic proxy on constructors that take arguments


I've tried to use the code Sun posted on their Proxy usage page, and I tried to use the DebugProxy to print which method is invoked. The thing is, the object I'm creating a proxy for, needs to have an argument. If I try to create the proxy with an argument to the constructor, I receive the following error :

Exception in thread "main" java.lang.ClassCastException: $Proxy0 cannot be cast to myPackage.myClass

I created the proxy like this :

MyClass mc = (MyClass) DebugProxy.newInstance(new MyClass(props));

How can I create a proxy instance, and still call the right constructor ?

Best Solution

TheJDK-generated proxy is not of the same class type as the object you're proxying. Instead, it implements the same interfaces of the target object. You need to cast to one of those interface types.

If you look at the example on the page you linked to, it's casting to Foo, not FooImpl.