I wish that I had authored this, but I only came across it. It has a line of code that reads System.out.println("meep");
and it prints, maddeningly, Nutn
.
import java.lang.reflect.*;
import java.util.*;
public class SomethingFun {
public static void main(String[] args) throws java.lang.Exception {
doSomething("meep");
System.out.println("meep");
}
public static void doSomething(String s) throws java.lang.Exception {
Field privateStringField = String.class.getDeclaredField("value");
privateStringField.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
// This line is where the trouble is:
modifiersField.setInt(privateStringField, privateStringField.getModifiers() & ~Modifier.FINAL);
privateStringField.set(s, new char[] {'N', 'u', 't', 'n'});
}
}
I've gathered a bit about the reflective classes - I suspect that it is messing around with the interning somehow. Can someone shed some light on what's going on here?
In particular, it is the line
modifiersField.setInt(privateStringField, privateStringField.getModifiers() & ~Modifier.FINAL);
that is so perplexing.