----此处是JDK动态代理----
package d18_5_2; public interface IDog { void info(); void run(); }
package d18_5_2; public class GunDog implements IDog { @Override public void info() { System.out.println("DunDog 我是一只猎狗!"); } @Override public void run() { System.out.println("GunDog 我奔跑迅速!"); } }
package d18_5_2; public class DogUtil { public void beforeMethod() { System.out.println("DogUtil beforeMethod"); } public void afterMethod() { System.out.println("DogUtil afterMethod"); } }
package d18_5_2; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyInvocationHandler implements InvocationHandler { // 需要被代理的对象 private Object target; public void setTarget(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { DogUtil du = new DogUtil(); du.beforeMethod(); Object result = method.invoke(target, args); du.afterMethod(); return result; } }
package d18_5_2; import java.lang.reflect.Proxy; public class MyProxyFactory { // 为指定target生成动态代理对象 public static Object getProxy(Object target) { // 创建一个MyInvocationHandler对象 MyInvocationHandler handler = new MyInvocationHandler(); // 为MyInvocationhandler指定target handler.setTarget(target); return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), handler); } }
package d18_5_2; public class TestDog { public static void main(String[] args) { IDog target=new GunDog(); IDog dog = (IDog)MyProxyFactory.getProxy(target); dog.info(); dog.run(); } }