| 12 | public class StringTest { |
| 13 | |
| 14 | public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { |
| 15 | String a = "123"; |
| 16 | //这里的 a 和 b 都是同一个对象,指向同一个字符串常量池对象。 |
| 17 | String b = "123" ; |
| 18 | String c = new String("123") ; |
| 19 | |
| 20 | System.out.println("a=b:" + (a == b)); |
| 21 | System.out.println("a=c:" + (a == c)); |
| 22 | |
| 23 | System.out.println("a=" + a); |
| 24 | |
| 25 | a = "456"; |
| 26 | System.out.println("a=" + a); |
| 27 | |
| 28 | |
| 29 | //用反射的方式改变字符串的值 |
| 30 | Field value = a.getClass().getDeclaredField("value"); |
| 31 | //改变 value 的访问属性 |
| 32 | value.setAccessible(true) ; |
| 33 | |
| 34 | char[] values = (char[]) value.get(a); |
| 35 | values[0] = '9' ; |
| 36 | |
| 37 | System.out.println(a); |
| 38 | } |
| 39 | } |