以下是视频中实现获取代理的方法,
public static Object getProxy(final Object target, final Advice advice){
Object proxy = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod();
Object obj = method.invoke(target, args);
advice.afterMethod();
return obj;
}
});
return proxy;
}
其中的这句:public Object invoke(Object proxy, Method method, Object[] args)中的第一个参数Object proxy好像是没有用到呢,到底有什么作用,我把代码稍稍修改了以下,结果还是一样的,就像下面这样
public static Object getProxy(final Object target, final Advice advice){
Object proxy = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
advice.beforeMethod();
proxy = method.invoke(target, args);
advice.afterMethod();
return proxy;
}
});
return proxy;
}
|