日期:2014-05-20  浏览次数:20631 次

怎么理解java中的 动态代理啊?怎么个动态法?
RT 希望各位说的通俗点

------解决方案--------------------
不好说 给你个例子吧

Java code

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");
    }
}