How to protect string from hacking

Can somebody tell me the changes should be made in String class API (we can't do that I know) so that following program should print "Earth" ? OR
How can we stop printing "Sun" ? How to stop hacking ?

public class StringAPI {
    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
        Field value = String.class.getDeclaredField("value");
        value.setAccessible(true);
        value.set("Earth", "Sun".toCharArray());
        System.out.println("Earth"); // prints "Sun"
    }
}
Jon Skeet
people
quotationmark

Just launch the JVM with an appropriate security manager which prevents reflection. You should run code you don't trust under a pretty stringent security manager.

You don't need to change the String class - just run in a tighter environment. If you're unable to control the environment like this, chances are you couldn't enforce your own "custom" String class anyway.

As an example:

c:\Users\Jon\Test>java -Djava.security.manager StringAPI
Exception in thread "main" java.security.AccessControlException: access denied 
    ("java.lang.RuntimePermission" "accessDeclaredMembers")
        at java.security.AccessControlContext.checkPermission(Unknown Source)
        at java.security.AccessController.checkPermission(Unknown Source)
        at java.lang.SecurityManager.checkPermission(Unknown Source)
        at java.lang.SecurityManager.checkMemberAccess(Unknown Source)
        at java.lang.Class.checkMemberAccess(Unknown Source)
        at java.lang.Class.getDeclaredField(Unknown Source)
        at StringAPI.main(StringAPI.java:5)

That's just using the default policy (when the security manager is enabled) but you can also specify a custom policy.

people

See more on this question at Stackoverflow