我理解的动态代理就是在不污染原来代码的前提下(也就是不改动原来的代码)做的代码增强
练习版本
public class TestAop {
public static void main(String[] args) {
Cat cat = new Cat(); //这是实现了food接口的类
Dog dog = new Dog(); //这也是是实现了food接口的类
/**
* Proxy类的newInstance()方法有三个参数:
*
* ClassLoader loader:
* 它是类加载器类型,你不用去理睬它,你只需要知道怎么可以获得它就可以了:MyInterface.class.getClassLoader()就可以获取到ClassLoader对象,没错,只要你有一个Class对象就可以获取到ClassLoader对象;
* Class[] interfaces:
* 指定newProxyInstance()方法返回的对象要实现哪些接口,没错,可以指定多个接口,例如上面例子只我们只指定了一个接口:Class[] cs = {MyInterface.class};
* InvocationHandler h:
* 它是最重要的一个参数!它是一个接口!它的名字叫调用处理器!无论你调用代理对象的什么方法,它都是在调用InvocationHandler的invoke()方法!
*/
//这就是生成的一个代理类
Food o = (Food) Proxy.newProxyInstance(Food.class.getClassLoader(), new Class[]{Food.class}, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println(args);
for (Object arg : args) {
System.out.println(arg);
}
Object invoke = method.invoke(dog, args); //第一个参数是要进行代理的类的实例对象,第二个参数是方法的参数
return invoke;
}
});
o.eat("sdfsdf");
}
}
通用版本
public class TestAop {
public static void main(String[] args) {
Cat cat = new Cat(); //这是实现了food接口的类
Dog dog = new Dog(); //这也是是实现了food接口的类
Food proxyInstance = (Food) Proxy.newProxyInstance(Food.class.getClassLoader(), new Class[]{Food.class}, new MyInvocationHandler(dog));
proxyInstance.eat("sdf");
}
}
class MyInvocationHandler implements InvocationHandler{
private Object object;
public MyInvocationHandler(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object invoke = method.invoke(object, args);
return invoke;
}
}