JDK动态代理

JDK会在内存中动态生成一个实现了指定接口的代理类的字节码,并通过类加载器加载这个类到JVM中。这个过程包括:

  • 分析目标接口,生成对应的代理类代码。
  • 利用Java反射API创建这个代理类的实例。
  • 将传入的InvocationHandler实例与代理类的实例关联起来。

接口定义

public interface DataConverterService {
    void convert();
}

接口实现类

public class DataConverterServiceImpl implements DataConverterService {
    @Override
    public void convert() {
        System.out.println("DataConverterServiceImpl convert");
    }
}

增加JDK动态代理实现类,需要实现InvocationHandler接口

public class DataConverterServiceHandler implements InvocationHandler {

private DataConverterService dataConverterService;

public DataConverterServiceHandler(DataConverterService dataConverterService) {
this.dataConverterService = dataConverterService;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("DataConverterServiceHandler 前");
method.invoke(dataConverterService, args);
System.out.println("DataConverterServiceHandler 后");
return null;
}
}

测试Main方法

public class DataConverterServiceMain {

    public static void main(String[] args) {
        DataConverterService dataConverterService = new DataConverterServiceImpl();
        DataConverterServiceHandler iComputerHandler = new DataConverterServiceHandler(dataConverterService);
        DataConverterService dataConverterProxy = (DataConverterService) Proxy.newProxyInstance(dataConverterService.getClass().getClassLoader(), dataConverterService.getClass().getInterfaces(), iComputerHandler);
        dataConverterProxy.convert();
    }
}

 

posted @ 2024-04-29 11:38  使用D  阅读(6)  评论(0编辑  收藏  举报