<< September 5, 2003 | Home | September 7, 2003 >>

Access Modifier

A thread of discussion scrolled by on a mailing list about reflective access in Java. I'll capture the essence of the discussion here.

Jeff Brown started with this:

Today I discovered something that I find alarming. Try this...

       String name = "Foo";
       Field field = String.class.getDeclaredField("value");

       // setAccessible is the key here...
       field.setAccessible(true);

       char[] cs = (char[])field.get(name);
       cs[0] = 'B';
       System.out.println("name = " + name);

This code has gained access to a private member in another class (String in this case) and modified that value. I have wandered around the immutability of a String. There are worse things I could do with this.

I am interested in hearing how other people feel about this. I think this is potential trouble. I understand that this will not work under most SecurityManagers, but this is still a concern I think. I think this means that you can't really rely on private members not being modified outside of your own code. I think this means you can't really rely on the "fact" that Strings are immutable.

Kevin Heifner pointed us to an interesting link:

Yep, If you want a good discuss of this "feature" see: http://www.javaspecialists.co.za/ Go to Newsletter -> Issue 014 "Insane Strings"

Enjoy, and don't let the C++ folks have all the "fun".

Mark Balbes was quick to humorize:

Obviously, someone misinterpreted the spec. Instead of an "immutable String" he wrote an "I'm mutable String".

:-)

I pointed out that Jeff's code and the code Kevin pointed to rely on implementation details. (In fact, they behave differently in GCJ, where various exceptions were thrown.)

Brian Gilstrap then gave this advice:

If you are worried about malicious third party libraries or malicious developers inside the company, have your program install a SecurityManager and stop worrying.

And of course, in keeping with the "Martin Fowler knows" theme of this month, here's a link from his Bliki: AccessModifier.