Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
SyntaxT3rr0r Avatar asked Dec 17 '22 11:12

SyntaxT3rr0r


1 Answers

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.!");
         }

     }
}
like image 62
Reverend Gonzo Avatar answered Dec 30 '22 16:12

Reverend Gonzo