java InvocationHandler用法举例
1、被代理对象
public interface AccountChange {
AccountChange deposit (double value);
AccountChange withdraw (double value);
double getBalance ();
}
2、代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ExampleInvocationHandler implements InvocationHandler {
private double balance;
@Override
public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
if ("deposit".equals(method.getName())) {
Double value = (Double) args[0];
System.out.println("deposit: " + value);
balance = balance + value;
return proxy;
}
if ("withdraw".equals(method.getName())) {
Double value = (Double) args[0];
System.out.println("withdraw: " + value);
balance = balance - value;
return proxy;
}
if ("getBalance".equals(method.getName())) {
// System.out.println("getBalance: " + balance);
return balance;
}
return null;
}
}
3、测试
import java.io.Serializable;
import java.lang.reflect.Proxy;
public class MyTest {
public static void main(String[] args){
MyTest myTest = new MyTest();
myTest.proxyTest();
}
public void proxyTest(){
AccountChange accountChange = (AccountChange) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {AccountChange.class, Serializable.class},
new ExampleInvocationHandler());
AccountChange ac = accountChange.deposit(100);
System.out.println("Balance: " + accountChange.getBalance());
System.out.println("Balance: " + ac.getBalance());
System.out.println(" " );
accountChange.withdraw(40);
System.out.println("Balance: " + accountChange.getBalance());
}
}
调用AccountChange对象(被代理)的任何一个方法,都会自动调用代理对象的invoke()方法,并且invoke()方法能获取到被代理对象正在被调用的方法和参数。
浙公网安备 33010602011771号