effect of changing String using reflection

后端 未结 7 605
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 17:54

As we all know, String is immutable in java. however, one can change it using reflection, by getting the Field and setting access level. (I know it is unadvised, I am not pl

7条回答
  •  心在旅途
    2020-12-03 18:09

    To demonstrate how can it screw up a program:

    System.out.print("Initial: "); System.out.println(addr);
    editIntStr("ADDR_PLACEH", "192.168.1.1");
    System.out.print("From var: "); System.out.println(addr);//
    System.out.print("Hardcoded: "); System.out.println("ADDR_PLACEH");
    System.out.print("Substring: "); System.out.println("ADDR_PLACE" + "H".substring(0));
    System.out.print("Equals test: "); System.out.println("ADDR_PLACEH".equals("192.168.1.1"));
    System.out.print("Equals test with substring: ");  System.out.println(("ADDR_PLACE" + "H".substring(0)).equals("192.168.1.1"));
    

    Output:

    Initial: ADDR_PLACEH
    From var: 192.168.1.1
    Hardcoded: 192.168.1.1
    Substring: ADDR_PLACEH
    Equals test: true
    Equals test with substring: false
    

    The result of the first Equals test is weird, isn't it? You can't expect your fellow programmers to figure out why is Java thinking they are equal...
    Full test code: http://pastebin.com/vbstfWX1

提交回复
热议问题