java proxy动态代理怎么实现

   2025-02-22 5440
核心提示:在Java中,可以通过使用java.lang.reflect.Proxy类来实现动态代理。首先,需要定义一个接口,代表被代理类和代理类都需要实现的

在Java中,可以通过使用java.lang.reflect.Proxy类来实现动态代理。

首先,需要定义一个接口,代表被代理类和代理类都需要实现的方法。

public interface Subject {void doSomething();}

然后,创建一个实现了该接口的被代理类。

public class RealSubject implements Subject {public void doSomething() {System.out.println("RealSubject do something");}}

接下来,创建一个代理类,实现InvocationHandler接口,并覆盖它的invoke方法。

import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class ProxyHandler implements InvocationHandler {private Object target;public ProxyHandler(Object target) {this.target = target;}public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// 在调用被代理类的方法之前,可以添加一些前置处理System.out.println("Before calling the method");// 调用被代理类的方法Object result = method.invoke(target, args);// 在调用被代理类的方法之后,可以添加一些后置处理System.out.println("After calling the method");return result;}}

最后,使用Proxy.newProxyInstance方法创建代理对象。

public class Main {public static void main(String[] args) {RealSubject realSubject = new RealSubject();ProxyHandler proxyHandler = new ProxyHandler(realSubject);// 创建代理对象Subject proxySubject = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),realSubject.getClass().getInterfaces(),proxyHandler);// 调用代理对象的方法proxySubject.doSomething();}}

运行上述代码,将会输出以下结果:

Before calling the methodRealSubject do somethingAfter calling the method

可以看到,通过动态代理,我们可以在调用被代理类的方法之前和之后添加一些额外的逻辑处理。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言