Java Proxy.newProxyInstance()引发类型转换异常?

时间:2019-01-07 01:46:18

标签: java class casting proxy instance

我的以下代码尝试创建一个代理对象,希望在调用“ say()”之前打印“ before”:

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

但是实际上它将抛出一个异常:

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

那我在哪里弄错了以及如何解决呢?

1 个答案:

答案 0 :(得分:2)

java.lang.reflect.Proxy只能强制转换为Interface,这行代码p.getClass().getInterfaces()将返回空接口,因为Person2没有实现任何功能,
因此,要解决此Person2,需要实施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);
    }
}

接口:

public interface IPerson {
   public void say();
}

然后在主要的静态方法中,可以将Proxy强制转换为Interface并调用该方法:

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