只是想知道,为什么发明 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;
}
}
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);
}
}
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
因为有些代码是可信代码——也就是说,如果本地应用程序想要这样做,也许这没什么大不了的。为了不受信任的代码,尽管如此——即小程序、Web 启动应用程序、RMI 存根或任何其他下载的代码——有一个SecurityManager
到位,(通常基于策略文件)有机会说“对不起,查理”并否认setAccessible()
要求。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)