Java怎么實現動態代理?
Java中實現動態代理主要依賴于java.lang.reflect.Proxy
類和java.lang.reflect.InvocationHandler
接口。動態代理可以用于在運行時創建代理類及其實例。以下是一個簡單的動態代理示例:
首先,定義一個接口:
public interface SomeInterface {void doSomething();String doAnotherThing(String input);
}
接下來,實現該接口的實際類:
public class SomeClass implements SomeInterface {public void doSomething() {System.out.println("Doing something...");}public String doAnotherThing(String input) {System.out.println("Doing another thing with input: " + input);return "Result for " + input;}
}
然后,編寫一個實現InvocationHandler
接口的類,用于處理代理對象的方法調用:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;public class MyInvocationHandler implements InvocationHandler {private Object target;public MyInvocationHandler(Object target) {this.target = target;}public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println("Before invoking method: " + method.getName());// 實際方法調用Object result = method.invoke(target, args);System.out.println("After invoking method: " + method.getName());return result;}
}
最后,使用Proxy.newProxyInstance
方法創建代理對象:
import java.lang.reflect.Proxy;public class DynamicProxyExample {public static void main(String[] args) {SomeInterface realObject = new SomeClass();// 創建代理對象SomeInterface proxy = (SomeInterface) Proxy.newProxyInstance(SomeInterface.class.getClassLoader(),new Class[] { SomeInterface.class },new MyInvocationHandler(realObject));// 調用代理對象的方法proxy.doSomething();String result = proxy.doAnotherThing("Hello");System.out.println("Result: " + result);}
}
在這個例子中,Proxy.newProxyInstance
方法創建了一個代理對象,該代理對象實現了SomeInterface
接口,并且調用該代理對象的方法時,MyInvocationHandler
中的invoke
方法會被調用。通過在invoke
方法中插入一些代碼,你可以在方法調用前后執行一些額外的邏輯。