动态代理类
package itbuluoge.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class DynamicProxy implements InvocationHandler{ private Object obj; public Object bind(Object obj) { this.obj=obj; return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(), this); } public Object invoke(Object arg0, Method method, Object[] args) throws Throwable { Object result=null; try { validateUser(); result=method.invoke(obj,args); } catch(Exception e) { e.printStackTrace(); } return result; } public void validateUser() { System.out.println("验证用户..."); } }
package itbuluoge.proxy; public class TestDynamic { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub DynamicProxy dp=new DynamicProxy(); ICompent com=(ICompent)dp.bind(new Compent()); com.bussiness1(); com.bussiness2(); com.bussiness3(); } }
输出结果
静态代理见文章:http://blog.csdn.net/itbuluoge/article/details/40046377