动态代理的定义?

动态代理是一种设计模式,它在运行时动态地创建并管理代理对象。与静态代理不同,动态代理不需要手动创建代理类,而是在运行时动态生成。这种方式更灵活,可以减少代码量,提高代码复用性。

动态代理的关键在于使用了反射机制。在Java中,可以使用java.lang.reflect.Proxy类来创建动态代理。这个类有一个newProxyInstance方法,可以生成一个实现指定接口的新的代理实例。这个方法需要三个参数:类加载器、一组接口、以及一个调用处理器(InvocationHandler)。调用处理器是一个实现了java.lang.reflect.InvocationHandler接口的对象,它定义了一个invoke方法,当对代理实例的方法进行调用时,这个方法会被执行。

下面是一个简单的Java动态代理的例子:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface MyInterface {
    void doSomething();
}

class MyRealClass implements MyInterface {
    public void doSomething() {
        System.out.println("Doing something...");
    }
}

class MyInvocationHandler implements InvocationHandler {
    private Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before invoking method...");
        Object result = method.invoke(target, args);
        System.out.println("After invoking method...");
        return result;
    }
}

public class Main {
    public static void main(String[] args) {
        MyRealClass realObj = new MyRealClass();
        MyInterface proxyObj = (MyInterface) Proxy.newProxyInstance(
            realObj.getClass().getClassLoader(),
            realObj.getClass().getInterfaces(),
            new MyInvocationHandler(realObj)
        );
        proxyObj.doSomething();
    }
}

在这个例子中,MyRealClass是真实的对象,MyInterface是它实现的接口。MyInvocationHandler是调用处理器,它在方法调用前后添加了日志输出。我们在main方法中创建了一个动态代理对象,并通过这个代理对象调用了doSomething方法。运行这段代码,你会看到在”Doing something…”前后分别输出了”Before invoking method…”和”After invoking method…”,这就是动态代理添加的额外功能。

发表评论

后才能评论