关于作业的代码实现: InvocationHandler logh=new LogHandler(m); Class
cls2=m.getClass(); Moveable m2=(Moveable)Proxy.newProxyInstance(cls2.getClassLoader(),cls2.getInterfaces(),logh); m2.move(); 请问一下,以上实现方式有啥问题,为什么会报错?
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); Subject subject = (Subject) Proxy.newProxyInstance(Client.class.getClassLoader(),new Class[]{Subject.class},new JdkProxySubject(new RealSubject())); subject.hello(); MathSubject mathSubject = new MathSubject(); InvocationHandler mathHandler= new ProxySubject(mathSubject); Class<?> cls = mathSubject.getClass(); Subject mathSubjectResult = (Subject) Proxy.newProxyInstance(Client.class.getClassLoader(), cls.getInterfaces(), mathHandler); InvocationHandler logmathHandler= new LogProxySubject(mathSubjectResult); Subject mathResult = (Subject) Proxy.newProxyInstance(Client.class.getClassLoader(), cls.getInterfaces(), logmathHandler); mathResult.hello("wahahaha"); mathResult.request();// 根据资料,添加了LogProxySubject, ProxySubjec , 替换了JdkProxySubject中的Class换为Interface 接口类Subject,这样就好了。
代理类实现的都是moveable接口,所以Class<?> cls = Car.getClass()这一行代码不用更改,删掉
Class cls2=m.getClass();类加载器和接口换回cls就好。
JDK 动态代理作业可以参考这个
https://github.com/imooc-java/proxy/blob/master/src/test/java/com/imooc/jdkproxy/HandlerTest.java
有什么错误,你贴出来塞
第二行应该改成 Class<?> clsw = m.getClass();