学了一点Java的reflection之后我发现貌似这个东西在Java里也可以实现,之前以为只有动态语言才能实现。
虽然我的试验(非常正常地)失败了,不过我相信问题出在个别细节上,因为还没有对reflection有非常系统的了解。
我把代码发上了,感兴趣的朋友欢迎指出问题啊
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class AccountProxy {
public BankAccount realAccount;
public AccountProxy(BankAccount realAccount) {
this.realAccount = realAccount;
}
public Object callMethod(String methodName, String ... params){
Class cls = realAccount.getClass();
try{
Method method=cls.getMethod(methodName);
Object returned= method.invoke(realAccount,params);
return returned;
}
catch (NoSuchMethodException e){
throw new IllegalArgumentException(cls.getName() + " does not support "+methodName);
}
catch (IllegalAccessException e){
throw new IllegalArgumentException("Insufficient access permission to call" +methodName + " in class "+ cls.getName());
}
catch (InvocationTargetException e){
throw new RuntimeException(e);
}
}
}
public class AccountProxyRunner {
public static void main(String[] args) {
AccountProxy firstAccount = new AccountProxy(new BankAccount("Shawn"));
firstAccount.callMethod("deposit","30");
System.out.println(firstAccount.callMethod("getBalance"));
}
}
以及被代理的
public class BankAccount {
private String owner;//will be directed assigned value to ensure uniqueness of bank owner
private double balance;
public BankAccount(String name) {
owner = name;
balance=0;
}
public void deposit(double amount){
balance += amount;
}
public void withdraw(double amount){
balance -=amount;
}
public double getBalance() {
return balance;
}
}
程序运行结果是抛出java.lang.IllegalArgumentException: BankAccount_Proxy.BankAccount does not support deposit
,发生了无方法异常。
然而去掉firstAccount.callMethod("deposit","30");之后下面的调用getBalance()能正常运行。