package com.sunsharing.practice; /** * Created by baich on 2016/2/24. */ public interface Animal { public void info(); }
package com.sunsharing.practice; /** * Created by baich on 2016/2/24. */ public class Cat implements Animal { public void info() { System.out.println("this is a cat, the language is miaomiao~"); } }
TraceHandler:
package com.sunsharing.practice; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; /** * Created by baich on 2016/2/24. */ public class TraceHandler implements InvocationHandler { private Object target; public TraceHandler(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("INFO: " + target.getClass().getName() + " staring..."); Object ob = method.invoke(target, args); System.out.println("INFO: " + target.getClass().getName() + " ending..."); return ob; } }
ProxyTest:
package com.sunsharing.practice; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Proxy; /** * Created by baich on 2016/2/24. */ public class ProxyTest { public static void main(String[] args) { Animal cat = new Cat(); InvocationHandler handler = new TraceHandler(cat); Object proxyObj = Proxy.newProxyInstance(cat.getClass().getClassLoader(), cat.getClass().getInterfaces(), handler); if (proxyObj instanceof Animal) { System.out.println("proxyObj is the instanceof Animal"); ((Animal) proxyObj).info(); } else { System.out.println("proxyObj is not the instanceof Animal"); } } }
以下是代理客户端的使用结果:
补充及参考资料:
代理对象是被代理对象接口的 实现,但并不是被代理对象类的子类。
参考资料:java动态代理实现: http://www.blogjava.net/thisliy/archive/2009/10/24/299621.html