Java的动态代理实现

来源:互联网 发布:传播学就业方向 知乎 编辑:程序博客网 时间:2024/06/07 13:32
  1. 实现InvocationHandler接口,重写invoke()方法
    • package proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class MyInvocationHandler implements InvocationHandler {    private Object target;    public MyInvocationHandler(Object target) {        super();        this.target = target;    }    @Override    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        System.out.println("---before method----");        Object result = method.invoke(target, args);        System.out.println("---after method----");        return result;    }    public Object getProxy() {        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),                target.getClass().getInterfaces(), this);    }}


  2. 定义接口类,该接口被被代理类和Proxy同时实现
    • package proxy;public interface UserService {    public void add();}


  3. 实现
    • package proxy;public class UserServiceImp implements UserService {    @Override    public void add() {        System.out.println("--add---");    }}


  4. Test
    • package proxy;public class ProxyTest {    public static void main(String [] args) {        UserService userService = new UserServiceImp();        MyInvocationHandler myInvocationHandler = new MyInvocationHandler(userService);        UserService proxy = (UserService) myInvocationHandler.getProxy();        proxy.add();    }}


原创粉丝点击