Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I 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 ?

like image 602
Geo Avatar asked Dec 17 '22 07:12

Geo


1 Answers

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.

like image 97
skaffman Avatar answered Dec 31 '22 15:12

skaffman