- 实现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); } }
- 定义接口类,该接口被被代理类和Proxy同时实现
package proxy; public interface UserService { public void add(); }
- 实现
package proxy; public class UserServiceImp implements UserService { @Override public void add() { System.out.println("--add---"); } }
- 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(); } }
Java的动态代理实现
最新推荐文章于 2023-12-06 21:47:54 发布