Search code examples
javastringmutable

Making a String really immutable


I've got a question but to get an answer the following fact has first to be accepted: in some cases, Java Strings can be modified.

This has been demonstrated in the Artima article titled: "hi there".equals("cheers !") == true

Link: http://www.artima.com/weblogs/viewpost.jsp?thread=4864

It still works nicely in Java 1.6 and it surely goes somehow against the popular belief that consists in repeating "Java Strings are always immutable".

So my question is simple: can String always be modified like this and are there any JVM security settings that can be turned on to prevent this?


Solution

  • You need to add a SecurityManager. This site has an example and explanation:

    Run with:

    java -Djava.security.manager UseReflection
    

    And the code:

    import java.lang.reflect.Field;
    import java.security.Permission;
    
    public class UseReflection {
        static{
            try {
                System.setSecurityManager(new MySecurityManager());
            } catch (SecurityException se) {
                System.out.println("SecurityManager already set!");
            }
    
        }
        public static void main(String args[]) {
            Object prey = new Prey();
            try {
                Field pf = prey.getClass().getDeclaredField("privateString");
                pf.setAccessible(true);
                pf.set(prey, "Aminur test");
                System.out.println(pf.get(prey));
            } catch (Exception e) {
                System.err.println("Caught exception " + e.toString());
            }
    
        }
    }
    
    class Prey {
        private String privateString = "privateValue";
    }
    
    class MySecurityManager extends SecurityManager {
         public void checkPermission(Permission perm) {
             if(perm.getName().equals("suppressAccessChecks")){
                 throw new SecurityException("Can not change the permission dude.!");
             }
    
         }
    }