1.需要被代理的类必须实现至少一个接口,如果使用cglib或者asm则不需要实现接口。
//接口
package com.aop;
public interface Calculator {
public double add();
public double mul();
}
//实现类
package com.aop;
public class XCalculator implements Calculator {
private int a = 90;
private int b = 38;
@Override
public double add() {
return a+b;
}
@Override
public double mul() {
// TODO Auto-generated method stub
return a-b;
}
}
2.实现代理逻辑的类必须实现invocationHandler接口,并且在使用反射调用方法前要添加自己的代码
package com.aop;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class CalculatorLoggingHandler implements InvocationHandler {
public CalculatorLoggingHandler(Object target) {
super();
this.target = target;
}
private Log log = new Log();
private Object target;
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log.info("the method" + method.getName() + "() begins with" + Arrays.toString(args));
Object result = method.invoke(target, args);
log.info("the method" + method.getName() + "() ends with " + result);
return result;
}
public static Object creatInstance(Class c, InvocationHandler in) {
return Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), in);
}
}
//主函数
package com.aop;
import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
Calculator xc = new XCalculator();
Calculator cal =(Calculator) CalculatorLoggingHandler.creatInstance(xc.getClass(), new CalculatorLoggingHandler(xc));
// System.out.println(xc.getClass().getClassLoader());
// System.out.println(xc.getClass().getInterfaces());
cal.add();
cal.mul();
}
}
运行结果
the methodadd() begins withnull
the methodadd() ends with 128.0
the methodmul() begins withnull
the methodmul() ends with 52.0
总结:
使用jdk事项动态代理比较简单,内部机制需要学习