代码实现
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
public class Test2 {
public static void main(String[] args) throws Exception{
Collection collection= (Collection) new MyProxyManger(new ArrayList(),new MyAdvice()).getProxy();
collection.add("xiaozhi");
collection.add("xiaozhi");
collection.remove("xiaozhi");
collection.size();
}
}
class MyProxyManger{
private Object target;
private Advice advice;
public MyProxyManger(Object target, Advice advice) {
super();
this.target = target;
this.advice = advice;
}
public Object getProxy() {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)throws Throwable
{
advice.beforeMehotd();
System.out.println(method.getName());
Object object=method.invoke(target, args);
advice.afterMehotd();
return object;
}
});
}
}
Advice
public interface Advice {
public abstract void beforeMehotd();
public abstract void afterMehotd();
}
MyAdvice
public class MyAdvice implements Advice {
@Override
public void beforeMehotd() {
System.out.println("-----------------我是方法前调用的!-----------------");
}
@Override
public void afterMehotd() {
System.out.println("-----------------我是方法后调用的!-----------------");
}
}
运行结果