解决Proxy.newProxyInstance创建动态代理导致类型转换错误的问题(xxx cannot be cast to xxx)

运行时报错

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to com.yabadun.mall.test.proxy.ShiXian
	at com.yabadun.mall.test.proxy.Test.main(Test.java:13)

代码

public class Test {
    public static void main(String[] args) {
        final JieKou jieKou = new ShiXian();
        JieKou jieKouProxy = (ShiXian) Proxy.newProxyInstance(jieKou.getClass().getClassLoader(), JieKou.class.getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("我开始说了");
                return method.invoke(jieKou, args);
            }
        });

        System.out.println(jieKou.say("hello"));

    }
}

要想分析其原因,还需要对Proxy.newProxyInstance方法进行了解,其原型为

java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader,Class<?>[] interfaces, InvocationHandler h) throwsIllegalArgumentException

问题就出现在第二个参数interfaces,api解释:the list of interfaces for the proxy class to implement,就是被代理类所实现的接口。而JieKou.class.getInterfaces()返回的是接口JieKou继承的上一级接口而已(如果有的话)

因此解决办法:

第二个传参修改为jieKou.getClass().getInterfaces(),或者改为ShiXian.class.getInterfaces(),再或者改为

new Class<?>[]{JieKou.class}

猜你喜欢

转载自blog.csdn.net/pange1991/article/details/81222616