views:

717

answers:

3

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 ?

+1  A: 

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.

skaffman
yeah. this sucks :). I was hoping DynamicProxy would be a quick way of doing this.
Geo
This kind of proxy is always interface-based, but other proxy generation libraries can proxy your class types directly. For example CGLIB can do this, and if you use CGLIB proxying via Spring's ProxyFactory, it's hilariously easy. Spring's ProxyFactory can generate either JDK proxies or CGLIB proxies, so it's a useful abstraction.
skaffman
+1  A: 

Does your class implement some interface you're trying to test? Proxy classes only implement methods from an interface. If you want to print before/after each method of a class (be it for metrics or debugging) I would suggesting using Aspect oriented programming (AOP). I've never done it myself, but I hear AspectJ is what you want.

public interface SomeInterface {
    public void someMethod();
}

public MyClass implements SomeInterface {
...
}

// DebugProxy doesn't return your class, but a class which implements all of the interfaces
// you class implements
SomeInterface mc = (SomeInterface ) DebugProxy.newInstance(new MyClass(props));
basszero
+1  A: 

When you want to create a proxy, you need to provide an interface to implement. Not a concrete class.

Interfaces do not describe constructors, so what you want to do is not immediately feasible.

Thorbjørn Ravn Andersen