解决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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值