Search code examples
javadynamicreflectionaopinterceptor

Java inheritance hack using dynamic proxy


I have 2 interfaces

public interface A{
  public void sayHello();
}

public interface B extends A{
 }

I have 1 class that implements interface A, let's say:

public class AImpl implements A{

public void sayHello(){
System.out.println("Hello");

}

}

Now i want to implement a dynamic proxy object for interface B using AImpl. Can I do that?

I tried it by the following code

InvocationHandler handler = new MyInvocationHandler(<AImplInstance>);
       B b= (B) Proxy.newProxyInstance(
                A.class.getClassLoader(),
                new Class[]{A.class},
                handler);
        b.sayHello();

And my invocation handler is :

public class MyInvocationHandler implements InvocationHandler{

    private A aImpl;


public MyInvocationHandler(A aImpl){
        this.aImpl= aImpl;
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return method.invoke(aImpl, args);
    }
}

I am getting class cast exception while typecasting proxy instance to B instance.


Solution

  • You haven't defined B as an interface of your proxy. Add it to the Class[].