package cn.heima.test2;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
public class Demo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList target=new ArrayList();
Advice_1 advice=new MyAdvice_1();
List proxy=(List)getProxy(target,advice);
proxy.add(232);
}
public static Object getProxy(final ArrayList target,final Advice_1 advice){
Object proxy=Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
// TODO Auto-generated method stub
advice.beforeMethod();
Object retVal=method.invoke(target, args);
return retVal;
}
});
return proxy;
}
}
class MyAdvice_1 implements Advice_1{
public void beforeMethod(){
System.out.println("方法前输出。。。。。");
}
}
interface Advice_1{
public abstract void beforeMethod();
} |