标签:ati oca throws ons code 调用 static imp printf
首先定义一个接口
public interface Subject { void printf(); }
被代理类实现接口
public class RealSubject implements Subject { @Override public void printf() { System.out.println("this is a RealSubject‘s printf()"); } }
定义SubjectInvocationHandler实现InvocationHandler接口
public class SubjectInvocationHandler implements InvocationHandler{ //被代理的对象 private Object proxy; public SubjectInvocationHandler(Object proxy) { this.proxy = proxy; } /** * proxy 调用方法的代理对象 * method 调用的方法 * args 调用方法的参数 * return 调用方法的返回值 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("SubjectInvocationHandler invoke prepare"); Object result = method.invoke(this.proxy, args); System.out.println("SubjectInvocationHandler invoke post"); return result; } }
最后测试
public class ProxyTest { public static void main(String[] args) { RealSubject realSubject = new RealSubject(); Class<?> clz = realSubject.getClass(); //获取代理类的class Class<?> proxyClz = Proxy.getProxyClass(clz.getClassLoader(), clz.getInterfaces()); try { //获取带InvocationHandler参数的构造器 Constructor<?> constructor = proxyClz.getConstructor(InvocationHandler.class); //利用构造器实例化代理对象 Subject proxySubject = (Subject) constructor.newInstance(new SubjectInvocationHandler(realSubject)); proxySubject.printf(); } catch (Exception e) { e.printStackTrace(); } //利用Proxy中的方法一步到位 Subject proxySubject = (Subject) Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), new SubjectInvocationHandler(realSubject)); proxySubject.printf(); } }
标签:ati oca throws ons code 调用 static imp printf
原文地址:http://www.cnblogs.com/wenhui92/p/7594484.html