Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection: Why are there methods like setAccessible()?

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
like image 203
Eng.Fouad Avatar asked Feb 19 '23 07:02

Eng.Fouad


1 Answers

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.

like image 65
Ernest Friedman-Hill Avatar answered Feb 28 '23 10:02

Ernest Friedman-Hill