public class JDKProxy implements InvocationHandler {
private Object target;
public JDKProxy(Object target) {
this.target = target;
}
public <T> T getProxy() {
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(target, args);
}
}
测试类
public class JDKProxyTest {
public static void main(String[] args) {
Person person = new Person();
person.setAge(18);
JDKProxy jdkProxy = new JDKProxy(person);
Person proxy = jdkProxy.getProxy();
System.out.println(proxy.toString());
}
}
错误:
Exception in thread "main" java.lang.ClassCastException: class com.sun.proxy.$Proxy0 cannot be cast to class lang.Person (com.sun.proxy.$Proxy0 is in unnamed module of loader 'app'; lang.Person is in module java11.test of loader 'app')
at java11.test/lang.JDKProxyTest.main(JDKProxyTest.java:16)
之前Person 也包 unnamed module,加了模块配置后,不提示了
只有代理类在报