package dynamicproxy;public interface SimpleInterface {void doSth();void doSthElse(String s);}
package dynamicproxy;public class RealObject implements SimpleInterface {@Overridepublic void doSth() {System.out.println("Real Object do sth");}@Overridepublic void doSthElse(String s) {System.out.println("Real Object do sth Else:"+s);}}
package dynamicproxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class DynamicProxyHandler implements InvocationHandler {private Object object;public DynamicProxyHandler(Object o){this.object=o;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("DynamicProxyHandler process.傳來的代理:"+ proxy.getClass());return method.invoke(object, args);}}
package dynamicproxy;import java.lang.reflect.Proxy;public class Test {static void consumer(SimpleInterface obj){obj.doSth();obj.doSthElse("你去處理一下");}/** * @param args */public static void main(String[] args) {RealObject obj=new RealObject();consumer(obj);SimpleInterface proxObj = (SimpleInterface) Proxy.newProxyInstance(SimpleInterface.class.getClassLoader(),new Class[] { SimpleInterface.class },new DynamicProxyHandler(obj));consumer(proxObj);}}