In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly talks about "are String objects immutable?", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "are String objects immutable?"
Note: this article is based on JDK8
String is believed to be a very basic class in Java, and it is also a favorite question in many primary interviews, including the pooling of String in JVM (constant pool), String's intern method, how to avoid memory spillovers (mainly before JDK1.7), etc., while String is an immutable object after creation, we will see from a variety of books, tutorials and interview books from the very beginning, but is this really the case? Do you have the right understanding of this immutability?
First, let's look at the following code:
String text = "hello:"; text + = "JoeKerouac"; System.out.println (text)
I'm sure most people will know that the above code will eventually print out "hello: JoeKerouac", which is our most common way to "change" a string, so why change it in quotation marks? Because this method does not really change the string itself, but recreates a new String object, and then points the text reference to the new object, the original String object "hello:" has not been changed, it seems that String really can not be changed, but there is really no way to change it? First of all, let's take a look at the class file of String. We can see that the char array used to store the actual data of the string is of type final, and the array does not have a corresponding get method, which looks perfect. What if you use reflection to change it? Let's go to the code:
Import java.lang.reflect.Field;public class StringTest {public static void main (String [] args) {String text = "JoeKerouac"; change (text); System.out.println (text) } / * change the string value, change the first character of the string to j * * @ param txt * the string to be changed * / static void change (String txt) {try {Field valueField = txt.getClass (). GetDeclaredField ("value"); valueField.setAccessible (true) Char [] value = (char []) valueField.get (txt); value [0] = 'jacks;} catch (IllegalAccessException e) {e.printStackTrace (); System.err.println ("current system does not allow reflection calls");} catch (NoSuchFieldException e) {}
Guess what the result is after the above code runs? It's "joeKerouac", yes, you guessed right, it's "joeKerouac" rather than "JoeKerouac". Let's look at another example:
Import java.lang.reflect.Field;public class StringTest {public static void main (String [] args) {String text = "JoeKerouac"; change (text); String textCopy = "JoeKerouac"; System.out.println (textCopy) } / * change the string value, change the first character of the string to j * * @ param txt * the string to be changed * / static void change (String txt) {try {Field valueField = txt.getClass (). GetDeclaredField ("value"); valueField.setAccessible (true) Char [] value = (char []) valueField.get (txt); value [0] = 'jacks;} catch (IllegalAccessException e) {e.printStackTrace (); System.err.println ("current system does not allow reflection calls");} catch (NoSuchFieldException e) {}
What is the result of the above code running? Smarter friends should guess, or "joeKerouac", there may be people will look confused, the last example can still understand, is to use reflection to change the text object, so the result is "joeKerouac", but this textCopy is declared after running the change method, why has it also been modified? This is because the literals of the two strings are the same, so in fact they both point to the same String object, which is Java pooling to String (of course, this is not the focus of this article), so when text is changed, textCopy is actually changed, and it also shows that although textCopy's declaration is on the next line of the change method call, he links to the same String object by some means like text before the change method call.
Some of the students here may think that this is over. The String object has indeed been changed by reflection, but what is the memory like at this time? Is the in-memory "JoeKerouac" the first declared string changed or is it just like the code snippet at the beginning of the article that just recreates an object and then points to the new object with a reference to the string, and the original object remains unchanged? In fact, we can probably guess, we are using reflection to change the value array in String, and not using public API to change, logically speaking, JVM is imperceptible, he should not and does not have the time to create a new > string and return, so is this the case? Let's look at the following example:
Import java.lang.reflect.Field;public class StringTest {public static void main (String [] args) throws InterruptedException {String text = "JoeKerouac"; System.out.println ("now text is:" + text); / / do heap dump Thread.sleep (1000 * 15) at this time; change (text); System.out.println ("now text is:" + text) / / re-heap dump Thread.sleep at this time (1000 * 60 * 60) } / * change the string value, change the first character of the string to j * * @ param txt * the string to be changed * / static void change (String txt) {try {Field valueField = txt.getClass (). GetDeclaredField ("value"); valueField.setAccessible (true) Char [] value = (char []) valueField.get (txt); value [0] = 'jacks;} catch (IllegalAccessException e) {e.printStackTrace (); System.err.println ("current system does not allow reflection calls");} catch (NoSuchFieldException e) {}
Perform heap dump operations in the above two comments respectively. It is recommended to use JVisual VM to facilitate subsequent operations. After the completion of heap dump, you can use JVisual VM to analyze the files from two dump, and you can use the OQL console in JVisual VM to query. The specific query statements are as follows:
Select {instance: s, content: s.toString (), id: objectid (s)} from java.lang.String s where s.toString () = = 'joeKerouac' | | s.toString () = =' JoeKerouac'
The final result should be that the first dump file will have a JoeKerouac string, the second dump file will have a joeKerouac string, and the ID of the two strings is the same, indicating that our guess above is correct, JVM did not create a new string to return, and we did do more > change the value of String, really change the value of memory.
We can see from the third piece of code that this method can be used to change the string defined when the user encodes. If there is a password string in your system and you happen to change the string with this method somewhere, if others do not know the reason why the adjustment can not be found for a long time, it is clearly stated that it is opposite, but printing is not correct. Haha ~ besides, if you encounter this problem one day, it may be some naughty kid who gives you a wave of this.
Finally, we see that String is not as immutable as the legend, relying on Java's powerful reflection system, even immutable objects like String can change ~ (PS: some security-demanding systems restrict the use of reflection)
At this point, I believe that you have a deeper understanding of "String objects are immutable?" you might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.