只是想知道,为什么发明 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);
    }
}

输出:
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 stub 或任何其他下载的代码——有一个 SecurityManager,它(通常基于策略文件)有机会说“对不起,查理”并拒绝 setAccessible() 请求。

10-08 19:26