标签:
package patterns.delegate; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; interface MyInterface { public void doSomething(); } class Myimplement implements MyInterface { public void doSomething() { System.out.println("call doSomething()"); } } //代理:为其他对象提供一种代理以控制对这个对象的访问。 class ProxyHandler implements InvocationHandler { private Object realOne; public ProxyHandler(Object realOne) { this.realOne = realOne; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 在转调具体目标对象前后,可以执行一些功能处理 // 转调具体目标对象的方法 Object object = method.invoke(realOne, args); //对方法进行过滤 if (method.getName().equals("someMethod")) { } return object; } public Object getProxy(){ return Proxy.newProxyInstance(getClass().getClassLoader(), realOne.getClass().getInterfaces(), this); } } public class DynamicProxy { public static void main(String args[]) { Myimplement real = new Myimplement(); MyInterface ss = (MyInterface) new ProxyHandler(real).getProxy(); ss.doSomething(); } }
标签:
原文地址:http://www.cnblogs.com/luangeng/p/5517307.html