MST
星途 面试题库

面试题:Java中如何通过反射创建接口的动态代理实例

请描述在Java中,利用反射和动态代理机制创建接口代理实例的主要步骤,并给出一个简单的示例代码,假设存在一个接口`SomeInterface`,包含一个方法`doSomething()`。
50.1万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

主要步骤

  1. 定义接口:定义需要代理的接口,如SomeInterface,包含需要代理的方法,例如doSomething()
  2. 实现InvocationHandler接口:创建一个类实现InvocationHandler接口,在invoke方法中编写代理逻辑,该方法接收目标对象、方法对象以及方法参数作为参数。
  3. 使用Proxy类创建代理实例:通过Proxy.newProxyInstance方法创建代理实例,该方法需要传入类加载器、目标接口数组以及InvocationHandler实例。

示例代码

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

interface SomeInterface {
    void doSomething();
}

class SomeInterfaceImpl implements SomeInterface {
    @Override
    public void doSomething() {
        System.out.println("实际方法执行");
    }
}

class ProxyHandler implements InvocationHandler {
    private Object target;

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

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理逻辑前置处理");
        Object result = method.invoke(target, args);
        System.out.println("代理逻辑后置处理");
        return result;
    }
}

public class ProxyExample {
    public static void main(String[] args) {
        SomeInterface target = new SomeInterfaceImpl();
        InvocationHandler handler = new ProxyHandler(target);
        SomeInterface proxy = (SomeInterface) Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),
                handler);
        proxy.doSomething();
    }
}