报错信息如下:
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();
}
}