我想知道,为什么发明Java的人会写像setAccessible(boolean flag)
这样的方法呢?它使得访问修饰符(尤其是private)变得无用,并且无法保护字段、方法和构造函数免受访问。请看下面这个简单的例子:
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
SecurityManager
,绝对可以防止JVM中的任何Java代码访问该成员。当然,本地代码或JVM外部的代码可能会做到这一点:但安全模型的目的不是防止计算机用户访问内存,而是防止不受信任的Java代码这样做。 - Ernest Friedman-Hilldefine private public
。访问修饰符在 C++ 中也不是“无用”的。 - Tom Hawtin - tackline