3

My following code tries to create a proxy-ed object that I expected to print "before" before calling "say()":

class Person2 {
    private String name;
    public Person2(String name) {
        this.name = name;
    }
    public void say() {
        System.out.println("Person:" + name);
    }
}
class MyHandler implements InvocationHandler {
    private Object object;
    public MyHandler(Object o) {
        object = o;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //
        System.out.println("before");
        return method.invoke(object, args);
    }
}
public class TestProxy {
    public static void main(String [] args) {
        Person2 p = new Person2("myName");
        InvocationHandler invocationHandler = new MyHandler(p);
        Person2 obj = (Person2) Proxy.newProxyInstance(
                p.getClass().getClassLoader(),
                p.getClass().getInterfaces(),
                invocationHandler);
        obj.say();
    }
}

But in fact it will throw out an exception:

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to Person2
at TestProxy.main

So where did I get wrong and how to fix it?

1
  • 2
    You can't proxy classes with java.lang.reflect.Proxy, only interfaces. Commented Jan 7, 2019 at 2:41

1 Answer 1

4

java.lang.reflect.Proxy can only be cast to Interface and also this line of code p.getClass().getInterfaces() would return empty interface because Person2 doesn't implement any,
so to fix this Person2 need to implement an Interface :

public class Person2 implements IPerson{
    private String name;
    public Person2(String name) {
       this.name = name;
    }
    @Override
    public void say() {
       System.out.println("Person:" + name);
    }
}

Interface :

public interface IPerson {
   public void say();
}

then in main static method, can cast Proxy to Interface and invoke the method :

public class TestProxy {
    public static void main(String [] args) {
       Person2 p = new Person2("myName");
       InvocationHandler invocationHandler = new MyHandler(p);
       IPerson obj = (IPerson) Proxy.newProxyInstance(
             p.getClass().getClassLoader(),
             p.getClass().getInterfaces(),
             invocationHandler);
       obj.say();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.