While trying to explain reflection to one my young friend, I finally ended up writing this code:
package aminur.test.mutate; import java.lang.reflect.Field; public class MutableString { public static void main(String[] argv) { mutate(); System.out.println("TRUE".equals("FALSE")); } public static void mutate() { try { String t = "TRUE"; String f = "FALSE"; Field val = String.class.getDeclaredField("value"); Field count = String.class.getDeclaredField("count"); Field off = String.class.getDeclaredField("offset"); val.setAccessible(true); count.setAccessible(true); off.setAccessible(true); count.set(t, f.length()); val.set(t, f.toCharArray()); off.set(f, off.getInt(f)); } catch (Exception e) { e.printStackTrace(); } } }
This won’t work in 1.3/.4 but will work in higher/lower version of JDK
The bug #5044412 fix(?) may disallow setting of value of fields.
Related posts
Feed
- India
- World
- Live
- Cricket News
This site uses cookies. These cookies come mainly from third party library used at this site(Google/Jetpack/etc). By continuing to use this website, you agree to their use.
To find out more, including how to control cookies, see here Cookie Policy
To find out more, including how to control cookies, see here Cookie Policy