package com.example.demo.test;
import com.alibaba.fastjson2.JSON;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
public class ProxyTest {
private interface Aspect<T> {
void before(T target, Method method, Object[] args);
void after(T target, Method method, Object[] args);
}
public static void main(String[] args) {
List<String> target = new ArrayList<>();
List<String> arrayList = newProxyInstance(target, new Aspect<List<String>>() {
@Override
public void before(List<String> target, Method method, Object[] args) {
if (method.getName().equals("add")) {
System.out.println("before add args" + JSON.toJSONString(args));
}
}
@Override
public void after(List<String> target, Method method, Object[] args) {
if (method.getName().equals("add")) {
System.out.println("after add args" + JSON.toJSONString(args));
}
}
});
arrayList.add("1");
arrayList.add("2");
arrayList.add("3");
arrayList.add("4");
System.out.println("OVER");
}
private static <T> T newProxyInstance(T target, Aspect<T> aspect) {
Class<?> clz = target.getClass();
return (T) Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), (proxy, method, args) -> {
aspect.before(target, method, args);
Object result = method.invoke(target, args);
aspect.after(target, method, args);
return result;
});
}
}
JDK动态代理
最新推荐文章于 2024-11-11 00:03:55 发布