package poxy; import javalangreflectInvocationHandler; import javalangreflectMethod; import javalangreflectProxy; /** * Simple Dynamic Proxy show a single interface a single instance case * * @author daniel zhou */ public class SimpleDynamicProxy { /** * @param args */ public static void main(String[] args) { //generate a hanlder ProxyHanlder hanlder=new ProxyHanlder(); /* * register instance to hanlder get the interfaces proxy */ Dog dogProxy=(Dog) hanldergenerateProxyHanlder(new Dog(){ @Override public String eat(String food) { return Daniels dog just ate an + food +!; } }); //do method by proxy String result = dogProxyeat(big bone); //take a look Systemoutprintln(result); } } //Proxy Handler class ProxyHanlder implements InvocationHandler{ //container Object obj = new Object(); public Object generateProxyHanlder(Object obj) { //store it thisobj = obj; //return interface proxy return ProxynewProxyInstance(objgetClass()getClassLoader() objgetClass()getInterfaces() this); } @Override public Object invoke(Object proxy Method method Object[] args) throws Throwable { Object result=null; result=methodinvoke(obj args); return result; } } //interface interface Dog{ String eat(String food); } 本文出自 专注JEE系列规范下的开源技术 博客请务必保留此出处 |