Java String是final类型,从不少书上咱们都知道String是不可变的,String是不就固若金汤了呢?no no....,java
咱们有万能的反射大法让他圆形毕露。String的源代码中有这么一个字段valuecode
/** The value is used for character storage. */ private final char value[]; /** Cache the hash code for the string */ private int hash; // Default to 0
好了,反射大法上路get
public static void main(String[] args) { String str = "zhang";//我姓张嚣张的张 try{ //我知道你的弱点 Field field = str.getClass().getDeclaredField("value"); //我要曝光你的隐私 field.setAccessible(true); //你很了不得吗,我立刻让你姓李 field.set(str,new char[]{'l','i'});// }catch (Exception e){ e.printStackTrace(); } System.out.println("str value:"+str);//不姓张了吧 }
最后验证了一句:No reflect ,No freemwork!string