Java String type value really not to be changed? __java

Source: Internet
Author: User
1.Java String can be changed.

It has always been assumed that the value of string types in Java cannot be modified, mainly because the string is final and there is no set method for setting the value. However, the value can be changed by reflection mechanism.

Example 1

public class Test {public
    static void Main (string[] args) throws Exception {
        String s= "0123456789";
        System.out.println ("Before Change: s=" + s);
        Field f = S.getclass (). Getdeclaredfield ("value");
        F.setaccessible (true);
        F.set (S, New char[]{' A ', ' B ', ' C '});
        System.out.println ("After change: s=" + s);
    }

Example 1 results:

Before change: s=0123456789
change: s=abc

Example 1 reasons

    There is a private final char value[member variable in the String class, and the value of the string class is stored in this value property. You can change this value by reflection to achieve the purpose of changing the string class value. By the same token, in this way

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.