标签:target JDK Object 代理 add InvocationHandler UserService 动态 public
Spring的AOP实现用了Proxy和InvocationHandler,现在就介绍一下JDK动态代理。
自定义的InvocationHandler需要重写3个函数。
1)构造函数,将代理对象传入
2)invoke方法
3)getProxy方法
1、创建业务接口
public interface UserService{
public void add();
}
2、创建业务接口实现类
public class UserServiceImpl implements UserService{
public void add(){
System.out.println("-----add-----");
}
}
3、创建自定义的InvocationHandler
public class MyInvocationHandler implements InvocationHandler{
//目标对象
private Object target;
public MyInvocationHandler(Object target){
super();
this.target=target;
}
4、执行目标对象的方法
public Object invoke(Object proxy, Method method, Object [] args)throws Throwable {
System.out.println("-----before-----");
Object result=method.invoke(target,args);
System.out.println("----after-----");
}
5、获取目标对象的代理对象
public Object getProxy(){
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),target.Class.getInstance(),this);
}
}
6、测试代理
public class ProxyTest{
@Test
public void testProxy()throws Throwable{
//实例化目标对象
UserService userService=new UserServiceImpl();
//实例化InvocationHandler
MyInvocaitonHanlder invovationHandler=new MyInvocationHandler(userService);
//根据目标对象生成代理对象
UserService proxy=(UserService) invocationHandler.getProxy();
//调用代理对象的方法
proxy.add();
}
}
7、测试结果
------before------
------add--------
------after-------
标签:target,JDK,Object,代理,add,InvocationHandler,UserService,动态,public 来源: https://www.cnblogs.com/jigang/p/12950966.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。