Skip to content

Instantly share code, notes, and snippets.

@caoxudong
Created January 15, 2014 06:49
Show Gist options
  • Save caoxudong/8431931 to your computer and use it in GitHub Desktop.
Save caoxudong/8431931 to your computer and use it in GitHub Desktop.
JDK中String类的实现不再是以往的(copy-on-write + 共享字符数组)了,而是每个字符串对象都有自己的字符数组
package problem.java.lang.reflect;
import java.lang.reflect.Field;
public class StringReflection {
/**
* $ java -version
* java version "1.7.0_45"
* Java(TM) SE Runtime Environment (build 1.7.0_45-b18)
* Java HotSpot(TM) 64-Bit Server VM (build 24.45-b08, mixed mode)
*/
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String s1 = "Hello World";
String s2 = "Hello World";
String s3 = s1.substring(6);
System.out.println(s1); // Hello World
System.out.println(s2); // Hello World
System.out.println(s3); // World
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
char[] value = (char[])field.get(s1);
value[6] = 'J';
value[7] = 'a';
value[8] = 'v';
value[9] = 'a';
value[10] = '!';
System.out.println(s1); // Hello Java!
System.out.println(s2); // Hello Java!
System.out.println(s3); // World
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment