/* * ReflectString.java * Version 1.0.0 * Created on 2017年12月15日 * Copyright ReYo.Cn */ package reyo.sdk.utils.test.reflect; import java.lang.reflect.Field; public class ReflectString { public static void main(String[] args) { String s1 = "reyo"; String s2 = "reyo"; String s3 = new String("reyo"); String s4 = new String(s1); System.out.println("s1==s2:" + (s1 == s2)); System.out.println("s1==s3:" + (s1 == s3)); System.out.println("s3==s4:" + (s3 == s4)); try { Field f = String.class.getDeclaredField("value"); System.out.print("Accessible: " + f.isAccessible()); f.setAccessible(true); System.out.println(" -> " + f.isAccessible()); char[] v = (char[]) f.get(s1);// 获取S1的内部value数组 System.out.print("\nvalue:"); System.out.println(v); v[0] = 'x';// 修改数组 v = new char[1];// 目测因为是get到的是引用的复制,这个引用改变不影响原引用 v[0] = 'y'; System.out.print("value:"); System.out.println(v); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("\ns1:" + s1 + "\ns2:" + s2 + "\ns3:" + s3 + "\ns4:" + s4); System.out.println("\ns1==s2:" + (s1 == s2)); System.out.println("s1==s3:" + (s1 == s3)); System.out.println("s3==s4:" + (s3 == s4)); } }
s1==s2:true
s1==s3:false
s3==s4:false
Accessible: false -> true
value:reyo
value:y
s1:xeyo
s2:xeyo
s3:xeyo
s4:xeyo
s1==s2:true
s1==s3:false
s3==s4:false