静态代理和动态代理详解
1.动态代理
我们实现动态代理需要Proxy类以及 InvocationHandler接口
如何创建代理类
class ProxyinvocationHandler implements inocationHandler{
//先获取到被代理对象
Object target;
//设置被代理类
public void setTarget(Object target){
this.target=target;
}
//获取到Proxy类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterface,this);
}
//重写invoke方法..隐示执行,如果代理类里要执行新方法就放入其中
public Object invoke(Object proxy,Mehod method,Object args[]){
Object result=method.invoke(target,args);
return result;
}
}
//测试类
class test{
public void main(String args[]){
//先创建将要被代理的对象
User user=new UserImp();
ProxyinvocationHandler pih=new ProxyinvocationHandler();
pih.setTarget(user);
//动态生成代理类
User proxy =(Object)pih.getProxy();
proxy.delete();
}
}
getProxy();
proxy.delete();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-urgIxxfW-1625119345072)(C:\Users\user\AppData\Roaming\Typora\typora-user-images\image-20210628231320718.png)]