动态代理的API

Proxy 动态代理类
- 生成代理对象:Proxy.newProxyInstance( 类加载器,接口数组,处理器 )
- 类加载器:对象.getClass( ).getClassLoader( )
- 接口数组-被代理类的所有接口:被代理对象.getClass( ).getInterfaces( )
- 处理器:代理对象调用方法时,会被处理器拦截
InvocationHandler 处理器接口
- 处理器的作用:拦截方法的执行
- 代理对象调用方法时,必须经过处理器的invoke( )方法
动态代理的角色分析

动态代理的模板代码
T t=(T)Proxy.newProxyInstance(
被代理对象.getClass().getClassLoader(),
被代理对象.getClass().getInterfaces();
(Object obj, Method method, Object[] args)->{
Object result = method.invoke(代理对象,args);
return result;
}
);
t.接口的方法() ;
应用实例
调用List集合remove( )时,删除指定的元素(包含重复的元素)
public static void main(String[] args1) {
List list = new ArrayList();
Collections.addAll(list, 2, 3, 5, 2, 7, 2, 9,5, 6);
System.out.println("调用方法前:"+list);
List listProxy=(List) Proxy.newProxyInstance(
list.getClass().getClassLoader(),
list.getClass().getInterfaces(),
(Object obj, Method method, Object[] args)->{
Object invoke = null;
if("remove".equals(method.getName())){
while(true){
if (!list.contains(args[0])) {
break;
}
list.remove(args[0]);
}
}else{
invoke = method.invoke(list, args);
}
return invoke;
}
);
listProxy.remove(2);
System.out.println("调用方法后:"+list);
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步