讓Java String值可變

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

相關文章
相關標籤/搜索