demo介绍: Foo_target这个对象有自己具体的业务实现,但是在方法执行前后需要一些准备事项的执行,所以需要一个代理者替自己负责整个运行过程;
定义Foo接口
public interface Foo { void doSomething(); }
定义Foo实现类Foo_target
public class Foo_target implements Foo{ @Override public void doSomething() { System.out.println("do my thing by myself..."); } }
定义InvocationHandler类实现
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class MyInvocationHandler implements InvocationHandler{ private Object target; public MyInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //代理对象在 要代理对象做事之前 先做的事儿 System.out.println("...pre..."); //要代理对象 做的事儿 Object o = method.invoke(target, args); //代理对象在 要代理对象做事之后 做的事儿 System.out.println("...end..."); return o; } }
运用动态代理
import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Proxy; public class ProxyClass { public static void main(String[] args) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { //InvocationHandler中的invoke方法是代理类在执行时需要做的具体事儿, 参数是要代理对象 InvocationHandler handler = new MyInvocationHandler(new Foo_target()); //根据要代理对象的类加载器及其接口,实现代理对象 Class proxyClass = Proxy.getProxyClass(Foo_target.class.getClassLoader(), new Class[] {Foo.class}); //为代理对象添加InvocationHandler,返回具体代理实例 Foo f = (Foo)proxyClass.getConstructor(new Class[]{InvocationHandler.class }).newInstance(new Object[]{handler}); //代理对象替代理人做事儿 f.doSomething(); System.out.println("-------------------------------------"); //法二 Foo f2 = (Foo)Proxy.newProxyInstance(Foo_target.class.getClassLoader(), Foo_target.class.getInterfaces(), handler); f2.doSomething(); } }