Just wondering, why did the people who invented Java write methods like setAccessible(boolean flag)
, which makes the access-modifiers (specially private) useless and cannot protect fields, methods, and constructors from being reached? Look at the following simple example:
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
Because some code is trusted code -- i.e., if a local application wants to do this, maybe it's not a big deal. For untrusted code, though -- i.e., an applet, or a web start application, or RMI stubs, or any other downloaded code -- there's a SecurityManager
in place, which (generally based on a policy file) has the opportunity to say "Sorry, Charlie" and deny the setAccessible()
request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With