Does the Java string type value really have to be changed?

Source: Internet
Author: User

Can 1.Java String be changed?

It has been assumed that the value of string 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 changed: S=ABC

Example 1 cause

There is a private final char value[] member variable in the String class, and the value of the string class is stored in the Value property. This value can be changed by reflection to achieve the purpose of changing the value of the string class. Similarly, in this way, we can change the private member variable of the custom object.

Does the Java string type value really have to be changed?

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.