核心: 代理模式&反射
核心类: InvocationHandler & Method
interface Run{
void run();
}
class Run1 implements Run{
@Override
public void run() {
System.out.println("run");
}
}
class MyHandler implements InvocationHandler{
private Run target;
public void setTarget(Run target){
this.target = target;
}
public void before(){
System.out.println("before");
}
@Override
public Object invoke(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
before();
arg1.invoke(target,arg2);
return null;
}
}
public class DynamicPattenTest {
public static void main(String[] args) throws IllegalArgumentException, InstantiationException, IllegalAccessException {
Run r = new Run1();
MyHandler h = new MyHandler();
h.setTarget(r);
Run r1 = (Run)Proxy.newProxyInstance(r.getClass().getClassLoader(), r.getClass().getInterfaces(), h);
r1.run();
}
}
AOP: 术语
Aspect:切面 就是想干吗,加log 或者权限 MyHandler
advice :具体的log方法。before();
pointcut:哪个类的哪个方法加log. run()
target:被代理对象。r