日期:2014-05-20 浏览次数:20666 次
package com.haojia.sample; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * jdk动态代理例子 * * @author jah * */ public class SecurityHandler implements InvocationHandler { private Object obj; public Object newProxy(Object obj) { this.obj = obj; return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj .getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { checkSecurity(); return method.invoke(obj, args); } public void checkSecurity() { // 可以在这里执行检查安全性的工作 System.out.println("checked"); } public static void main(String[] args) { SecurityHandler sh = new SecurityHandler(); TestInterface o = (TestInterface) sh.newProxy(new TestClass()); o.go(); } } interface TestInterface { void go(); } class TestClass implements TestInterface { public void go() { System.out.println("go"); } }