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;
}