Line creation is really immutable

I have a question, but in order to get the answer, first of all you need to accept the following fact: in some cases, Java strings can be changed.

This was demonstrated in an Artima article entitled "Hello there." .Quals ("cheers!") == true

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

It still works well in Java 1.6, and it certainly does in some way contradict the popular belief that repeating "Java strings are always immutable."

So my question is simple: is it possible to change a String like this like this, and are there any JVM security settings that can be enabled to prevent this?

+4
source share
2 answers

You need to add SecurityManager. This site contains 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.!"); } } } 
+7
source

All reflection operations are verified by the SecurityManager installation.

And if you are worried about malicious code, you should still have a SecurityManager . If not, then I would not bother. If people want to shoot desperately in the foot, they should be allowed to.

+5
source

All Articles