jdk动态代理 案例
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; interface Person1 { public String eat(); public String drink(); } class Kid implements Person1{ public String name; public Kid(String name) { this.name=name; } public String eat() { System.out.println("kids are eating!"); return this.name; } public String drink() { System.out.println("kids are drinking!"); return this.name; } } class MyInvocationHandler<T> implements InvocationHandler{ //被代理对象 private T target; public MyInvocationHandler(T target){ this.target=target; } /** * */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result; if("eat".equals(method.getName())) { System.out.println("洗手"); result = method.invoke(target, args); System.out.println("刷碗"); }else { result = method.invoke(target, args); } return result; //反射方法的返回值 } } public class ProxyDemos { public static void main(String[] args) throws NoSuchMethodException, SecurityException, Throwable { Person1 p=new Kid("小王"); MyInvocationHandler<Person1> handle=new MyInvocationHandler<Person1>(p); Person1 kid=(Person1) Proxy.newProxyInstance(Person1.class.getClassLoader(), new Class<?>[]{Person1.class}, handle); System.out.println(kid.eat()); System.out.println("--------------------"); System.out.println(kid.drink()); } }
Output:
洗手
kids are eating!
刷碗
小王
--------------------
kids are drinking!
小王