先定义一个接口,根据代理模式的原理,被代理类与代理类都要实现它。java
public interface Person { void eat(); }
再写一个实际执行任务的类(被代理类):ide
public class RealPerson implements Person { @Override public void eat() { System.out.println("I am eating"); } }
代理类的写法:写一个InvocationHandler的子类this
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class PersonProxyHandler implements InvocationHandler { private Person man; public PersonProxyHandler(Person man) { this.man = man; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before eating"); Object res = method.invoke(man, args); System.out.println("after eating"); return res; } }
按照常规想法,代理类要拥有一个被代理类对象的引用,而后在invoke方法中,method.invoke(man, args); 这一句代码代表对实际对象的调用,其他代码就是AOP加强了。spa
主类:代理
import java.lang.reflect.Proxy; public class Solution { public static void main(String[] args) { RealPerson man = new RealPerson(); PersonProxyHandler realHandler = new PersonProxyHandler(man); Person proxy = (Person) Proxy.newProxyInstance( Person.class.getClassLoader(), new Class[]{Person.class}, realHandler); proxy.eat(); } }
运行main方法,控制台打印以下:code
before invoke
is eating
after invoke对象
这种代理方式也称为“JDK动态代理”blog