动态代理详解(一)应用示例

来源:互联网 发布:法国大革命 评价 知乎 编辑:程序博客网 时间:2024/06/08 11:56
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class MyInvocationHandler implements InvocationHandler{    // 目标对象    private Object target;    /**     * 构造方法     * @param target 目标对象     */    public MyInvocationHandler(Object target) {        super();        this.target = target;    }    /**     * 执行目标对象的方法     */    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        // 在目标对象的方法执行之前简单的打印一下        System.out.println("--------before-------");        // 执行目标对象的方法        Object result = method.invoke(target, args);        // 在目标对象的方法执行之后简单的打印一下        System.out.println("--------after--------");        return result;    }    /**     * 获取目标对象的代理对象     * @return 代理对象     */    public Object getProxy() {        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),                target.getClass().getInterfaces(), this);    }}
public interface UserService {    /**     * 目标方法     */    public abstract void add();}
public class UserServiceImpl implements UserService{    public void add() {        System.out.println("-------add------");    }}
import org.junit.Test;public class ProxyTest {    @Test    public void testProxy() throws Throwable {        // 实例化目标对象        UserService userService = new UserServiceImpl();        // 实例化InvocationHandler        MyInvocationHandler invocationHandler = new MyInvocationHandler(userService);        // 根据目标对象生成代理对象        UserService proxy = (UserService) invocationHandler.getProxy();        // 调用代理对象的方法        proxy.add();    }}

运行结果:

------------------before--------------------------------------add----------------------------------after------------------
0 0
原创粉丝点击