InvocationHandler是什麼

人在代码在發表於2024-09-23

`InvocationHandler`是Java中的一個介面,用於處理透過代理物件的方法呼叫。它主要應用於動態代理機制,允許在執行時動態地建立代理類和其例項。`InvocationHandler`的主要作用包括:

1. **攔截方法呼叫**:當代理物件的方法被呼叫時,`InvocationHandler`的`invoke`方法會被觸發。這使得你可以在方法呼叫前後新增自定義邏輯,例如日誌記錄、許可權檢查、事務管理等。

2. **動態代理**:透過使用`Proxy`類和`InvocationHandler`介面,可以在執行時建立實現一個或多個介面的代理例項,而不需要預先定義這些代理類。這種機制非常靈活,適用於如AOP(面向切面程式設計)等場景。

3. **解耦和靈活性**:使用動態代理可以使程式碼更加解耦,減少硬編碼,同時提高系統的靈活性和可維護性。

以下是一個簡單的示例,展示瞭如何使用`InvocationHandler`來建立一個動態代理:

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

// 定義一個介面
interface MyInterface {
void myMethod();
}

// 實現介面的真實類
class RealClass implements MyInterface {
@Override
public void myMethod() {
System.out.println("RealClass: myMethod()");
}
}

// 建立InvocationHandler實現類
class MyInvocationHandler implements InvocationHandler {
private Object realObject;

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

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

public class Main {
public static void main(String[] args) {
// 建立真實物件
MyInterface realObject = new RealClass();

// 建立代理物件
MyInterface proxyInstance = (MyInterface) Proxy.newProxyInstance(
realObject.getClass().getClassLoader(),
realObject.getClass().getInterfaces(),
new MyInvocationHandler(realObject)
);

// 呼叫代理物件的方法
proxyInstance.myMethod();
}
}
```

在這個示例中,`MyInvocationHandler`實現了`InvocationHandler`介面,並在`invoke`方法中新增了方法呼叫前後的日誌列印。透過`Proxy.newProxyInstance`方法建立了一個代理物件,當呼叫代理物件的`myMethod`方法時,會首先執行`invoke`方法中的邏輯。

相關文章