动态代理对象的创建---------------理解了这段代码,你就懂了动态代理了
2013-08-14 10:52
417 查看
JDK中:
java.lang.reflect
类 Proxy
java.lang.Object java.lang.reflect.Proxy
创建某一接口
Foo的代理:
InvocationHandler handler = new MyInvocationHandler(...); Class proxyClass = Proxy.getProxyClass( Foo.class.getClassLoader(), new Class[] { Foo.class }); Foo f = (Foo) proxyClass. getConstructor(new Class[] { InvocationHandler.class }). newInstance(new Object[] { handler });
或使用以下更简单的方法:
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, handler);
//////////////////////////////////////////////////////////实例测试如下
///上面部分的复杂方式
Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
Collection proxy1 = (Collection)constructor.newInstance(new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod(method);
Object retVal = method.invoke(target, args);
advice.afterMethod(method);
return retVal;
}
});
、////更简洁方式
private static Object getProxy(final Object target,final Advice advice) {//传递目标对象和切面类
Object proxy3 = Proxy.newProxyInstance(//用newProxyInstance方式得到目标类的代理实例对象
target.getClass().getClassLoader(),//参数一:目标类的类加载器
/*new Class[]{Collection.class},*/
target.getClass().getInterfaces(),//参数二:目标类的接口类
new InvocationHandler(){//参数三:Handler对象 (此处参数用‘匿名内部类’!)
//client程序调用objProxy.add("abc")方法时,就会去调用invoke方法,所以涉及三要素(即:invoke(objProxy对象、add方法、"abc"参数))
public Object invoke(Object proxy, Method method, Object[] args)//在代理实例上处理方法调用并返回结果。在与方法关联的代理实例上调用方法时,将在调用处理程序上调用此方法
throws Throwable {
advice.beforeMethod(method);//切面方法(处理事务,日志等)(AOp思想)
Object retVal = method.invoke(target, args);//对带有指定参数的指定对象调用由此
Method对象表示的底层方法。(即调用目标类target中相对应的底层方法)
advice.afterMethod(method);//切面方法(处理事务,日志等))(AOp思想)
return retVal;
}
}
);
return proxy3;
}
相关文章推荐
- createElement动态创建HTML对象脚本代码
- createElement动态创建HTML对象脚本代码
- java动态代理对象实例的创建
- 通过代码组织,让你更好的理解和使用JDK动态代理
- 黑马程序员--09.动态与代理AOP--03【InvocationHandler接口】【通过反射创建动态代理类对象】
- 《C++编程思想》 第十二章 动态对象创建 (原书代码+习题+解答)
- jdk与cglib动态代理目标对象创建对比
- 41-知识补充(UIPickerView的补充方法,使用self创建对象的好处,id和instancetype区别,KVC底层代码实现,文本框的两个代理方法)
- 关于创建静态内部类的对象的理解代码
- JAVA动态代理模式(从现实生活角度理解代码原理)
- 动态创建客户端端代理代码
- 浅谈模拟java动态代理(自己的理解,里面代码是马士兵老师的代码)
- 动态创建对象演示代码MenuFunction ClassFactory FormRun ReportRun
- JAVA动态代理模式(从现实生活角度理解代码原理)
- 关于使用动态代理创建代理对象是报错 java.lang.ClassCastException: $Proxy0 cannot be cast to 的解决办法
- 通过反射创建动态代理对象(三)
- 通过反射创建动态代理对象(二)
- Spring AOP高级——源码实现(3)AopProxy代理对象之JDK动态代理的创建过程
- 设计模式——代理模式(理解静态代理和动态代理+代码)
- unity3d通过代码动态创建销毁游戏对象