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);
}
}
出力:
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