Question

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
Was it helpful?

Solution

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.

OTHER TIPS

Well, once you have released a Java program, anyone is free to reverse engineer, or de-compile, it anyways, so if someone wanted it badly enough, they would probably be able to access your your "privates" anyway.

What you can do however, is to forbid any foreign code to access your stuff in your runtime. That is, if you're for instance using someone else's code you could disable reflections, access to files etc before those libraries are used.

Search for ClassLoader and Security Manager to find out more. Here's something that looks relevant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top