Eng*_*uad 4 java reflection language-design access-modifiers
只是想知道,为什么发明Java的人会编写类似的方法setAccessible(boolean flag)
,这会使访问修饰符(特别是私有的)无用,无法保护字段,方法和构造函数不被覆盖?请看以下简单示例:
public class BankAccount
{
private double balance = 100.0;
public boolean withdrawCash(double cash)
{
if(cash <= balance)
{
balance -= cash;
System.out.println("You have withdrawn " + cash + " dollars! The new balance is: " + balance);
return true;
}
else System.out.println("Sorry, your balance (" + balance + ") is less than what you have requested (" + cash + ")!");
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
import java.lang.reflect.Field;
public class Test
{
public static void main(String[] args) throws Exception
{
BankAccount myAccount = new BankAccount();
myAccount.withdrawCash(150);
Field f = BankAccount.class.getDeclaredFields()[0];
f.setAccessible(true);
f.set(myAccount, 1000000); // I am a millionaire now ;)
myAccount.withdrawCash(500000);
}
}
Run Code Online (Sandbox Code Playgroud)
OUTPUT:
Sorry, your balance (100.0) is less than what you have requested
(150.0)! You have withdrawn 500000.0 dollars! The new balance is: 500000.0
Run Code Online (Sandbox Code Playgroud)
因为某些代码是可信代码 - 即,如果本地应用程序想要这样做,也许这不是什么大问题.但是对于不受信任的代码 - 例如,applet,或者Web启动应用程序,或者RMI存根,或者任何其他下载的代码 - 都有一个SecurityManager
位置,(通常基于策略文件)有机会说"对不起" ,查理"并否认了这一setAccessible()
要求.