面试被虐的小lala 2022-04-08 23:44 采纳率: 33.3%
浏览 44
已结题

在练习jdk动态代理时出现的问题

报错信息如下:

Exception in thread "main" java.lang.ClassCastException: class jdk.proxy1.$Proxy0 cannot be cast to class com.qian.dao.StudentDao (jdk.proxy1.$Proxy0 is in module jdk.proxy1 of loader 'app'; com.qian.dao.StudentDao is in unnamed module of loader 'app')
    at TTT.text.main(text.java:12)

接口:

package com.qian.dao;

public interface dao {
    void dd();
}


实现类:


```java

package com.qian.dao;

import lombok.Data;

@Data
public class StudentDao implements dao{
    public void dd(){
        System.out.println("你好");
    }
}

代理类:
public class ProxyInvocation implements InvocationHandler {
    //被代理的接口
    private Object target;

    public void setTarget(Object target) {
        this.target = target;
    }

    //生成得到代理类
    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                this);
    }

    /**
     * Proxy.newProxyInstance(JdbcPool.class.getClassLoader(), conn.getClass().getInterfaces(), hander);
     *
     * Proxy.newProxyInstance(JdbcPool.class.getClassLoader(), new Class[]{com.mysql.jdbc.Connection.class}, hander)
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    //处理代理实例
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //Log(method.getName());
        return method.invoke(target.getClass().newInstance(), args);
    }
}

测试类:
public class text {
    public static void main(String[] args) {
        dao studentDao=new StudentDao();
        ProxyInvocation invocation = new ProxyInvocation();
        invocation.setTarget(studentDao);
        StudentDao proxy = (StudentDao) invocation.getProxy();
        proxy.dd();
    }
}


  • 写回答

2条回答 默认 最新

  • terfation 2022-04-09 00:36
    关注

    Proxy.newProxyInstance的第一个参数改为target的类加载器

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 7月4日
  • 创建了问题 4月8日