接口文件
package com.demo.service;
public interface Animal {
public void eat();
}
实现类
package com.demo.service.impl;
import com.demo.service.Animal;
public class Dog implements Animal {
public void eat() {
System.out.println("dog eat");
}
}
package com.demo;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler() {
}
public MyInvocationHandler(Object target){
this.target = target;
}
public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable {
System.out.println("before eat");
Object result = arg1.invoke(target, arg2);
System.out.println("after eat");
return result;
}
}
package com.demo;
import java.lang.reflect.Proxy;
import com.demo.service.Animal;
import com.demo.service.impl.Dog;
public class TestProxy {
public static void main(String[] args) {
Animal dog = new Dog();
MyInvocationHandler myInvocationHandler = new MyInvocationHandler(dog);
Animal animal = (Animal)Proxy.newProxyInstance(dog.getClass().getClassLoader(),dog.getClass().getInterfaces(), myInvocationHandler);
animal.eat();
}
}
AOP就是通过动态代理的方式实现的。
网友评论