Friday, March 19, 2010

On Java's (supposedly) immutable strings

The power of setAccessible is beyond belief.
import java.lang.reflect.*;

public class MutableStrings {
   public static void main(String args[]) throws Exception {
      Field value = String.class.getDeclaredField("value");
      value.set("foo", "bar".toCharArray());      

      System.out.println("foo"); // prints "bar"
Note: Although I label this post as [fun], I don't think it actually is...


  1. Wouldn't the security manager normally prevent this though? If you find this disturbing, wait till you start looking at Python.

  2. The impression I got is that a properly configured security manager is the exception rather than the norm, and you should never assume that one exist to offer you any protection from malicious intent.

    And if a security manager is preventing this, it's also preventing a lot of other things that are legitimate.