Simple Java code that works well, but functions in a way that is somewhat complicated

The following simple Java program displays the string Hello World through the statement System.out.println("Hello World"); but this is not so. He just replaces it with another line, which in this case is, Good day! and displays it on the console. The string Hello World is not displayed at all. Let's look at the following simple piece of code in Java.

 package goodday; import java.lang.reflect.Field; final public class Main { public static void main(String[] args) { System.out.println("Hello World"); } static { try { Field value = String.class.getDeclaredField("value"); value.setAccessible(true); value.set("Hello World", value.get("Good Day !!")); } catch (Exception e) { throw new AssertionError(e); } } } 

Only one question about this code here. It works exactly as expected, but I cannot reduce the length of the string. Good day! . If an attempt is made to do this, it raises a java.lang.ArrayIndexOutOfBoudsException . If the length is increased, the program works well, but the remaining characters in the display line are truncated, meaning that the length of both lines should be somewhat the same. What for? This is what I could not understand.

+6
source share
1 answer

The value field is a char[] that internally stores an array of characters that the string uses as storage. Other fields indicate the initial offset into the character array and the length of the string. (To take a substring, it simply creates a new String object that references the same char[] , but with a different starting offset and length.)

If you change these fields, you can do almost anything you want with a string. Example:

 import java.lang.reflect.Field; public class Test { // Obviously in real code you wouldn't use Exception like this... // Although hacking string values with reflection is worse, of course. public static void main(String[] args) throws Exception { System.out.println("Hello World"); replaceHelloWorld("Goodbye!"); System.out.println("Hello World"); replaceHelloWorld("Hello again!"); System.out.println("Hello World"); } static void replaceHelloWorld(String text) throws Exception { // Note: would probably want to do hash as well... copyField(text, "Hello World", "value"); copyField(text, "Hello World", "offset"); copyField(text, "Hello World", "count"); } static void copyField(String source, String target, String name) throws Exception { Field field = String.class.getDeclaredField(name); field.setAccessible(true); field.set(target, field.get(source)); } } 
+7
source

Source: https://habr.com/ru/post/901241/


All Articles