动态代理实现例子2:

import java.util.List; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Vector; public class VectorProxy implements InvocationHandler { private Object proxyObj; public VectorProxy(Object obj) { this.proxyObj = obj; } public static Object factory(Object obj) { Class<?> classType = obj.getClass(); return Proxy.newProxyInstance(classType.getClassLoader(), //类加载器随便指定一个就可以 classType.getInterfaces(), new VectorProxy(obj)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before calling: " + method); // 打印出方法参数 if (args != null) { for (Object obj : args) { System.out.println(obj); } } // 调用方法 Object object = method.invoke(proxyObj, args); System.out.println("After calling: " + method); return object; } public static void main(String[] args) { List v = (List) factory(new Vector()); System.out.println(v.getClass().getName()); v.add("New"); v.add("York"); System.out.println(v); v.remove(0); System.out.println(v); } }
动态代理实现例子3:
这个例子中定义了一个接口:
public interface Foo { public void doAction(); }
这个接口有两个实现类:
public class FooImpl1 implements Foo { @Override public void doAction() { System.out.println("From Implement 1 !"); } } public class FooImpl2 implements Foo { @Override public void doAction() { System.out.println("From Implement 2 !"); } }
定义invocation handler,其中的set方法使得实际对象是可更换的:
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class CommonInvocationHandler implements InvocationHandler { private Object target; public CommonInvocationHandler() { } public CommonInvocationHandler(Object obj) { this.target = obj; } public void setTarget(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(target, args); } }
使用:
import java.lang.reflect.Proxy; public class Demo { public static void main(String[] args) { CommonInvocationHandler handler = new CommonInvocationHandler(); Foo f = null; handler.setTarget(new FooImpl1()); f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, handler); f.doAction(); System.out.println("----------------------------"); handler.setTarget(new FooImpl2()); f.doAction(); } }
程序运行后输出:
From Implement 1 !
----------------------------
From Implement 2 !