技术要求:将系统功(例如:日记、统计等信息)能添加代理对象上
技术要点:
//获取proxy对象,将系统功能添加到代理中
private static Object getProxy(final Object proxied, final Advice advice){
return Proxy.newProxyInstance(
proxied.getClass().getClassLoader(),
proxied.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
//....
advice.beforeMethod();
Object retVal = method.invoke(proxiec, args);
advice.afterMethod();
//....
return retVal;
}
});
}
//系统功能
public interface Advice{
void beforeMethod(Method method);
void afterMethod(Method method);
}
public class MyAdvice emplements Advice{
public void beforeMethod(Method method){
System.out.println(method.getName() + "-Advice-" + "beforeMethod");
}
public void afterMethod(Method method){{
System.out.println(method.getName() + "-Advice-" + "afterMethod");
}
}
//main
ArrayList proxied = new ArrayList();
Collection collectionProxy = (Collection)getProxy(proxied, new Advice());
collectionProxy.add("aaa");
collectionProxy.add("ccc");
collectionProxy.add("bbb"); |
|