在面试的时候可能经常会被问到,String是否是可变的,我觉得String是可变的!你们觉得了?
public class T { /** * @param args */ public static void main(String[] args)throws Exception { // TODO Auto-generated method stub String s = "1"; System.out.println(s); c(s); System.out.println(s); } public static void c(String s)throws Exception{ Field f = s.getClass().getDeclaredField("value"); f.setAccessible(true); Object o = f.get(s); char[] c = (char[]) o; f.set(s, "5".toCharArray()); //System.out.println(s); }}
结果是
1
5