Question

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 ?

Was it helpful?

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.

OTHER TIPS

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));

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top