jdk动态代理为什么必须实现接口
使用jdk生成代理类
通过jdk实现的动态代理会使用Proxy的newProxyInstance方法:

写一个类实现InvocationHandler,内部要注入对应原代理类的实现;

测试代码:
TestServiceImpl testService = new TestServiceImpl();
TestServiceImplHandler testServiceImplHandler = new TestServiceImplHandler(testService);
TestService testServiceProxy = (TestService)Proxy.newProxyInstance(testService.getClass().getClassLoader(), testService.getClass().getInterfaces(), testServiceImplHandler);
testServiceProxy.test();

看到生成的代理类父类是Proxy类,通过jdk代理生成的类都继承Proxy类:
因为Java是单继承的,而代理类又必须继承自Proxy类,所以通过jdk代理的类必须实现接口.
生成代理的字节码
还可以通过生成代理类的字节码查看,
package java.lang.reflect;包的Proxy类

通过将生成一半的代理类写到文件里面去:

生成的文件:

世界上所有的不公平都是由于当事人能力不足造成的.

浙公网安备 33010602011771号