The following simple Java program appears to display the string Hello World through the statement System.out.println("Hello World");
but it doesn't. It simply replaces this with another string which is in this case, Good Day !! and displays it on the console. The string Hello World is not displayed at all. Let's look at the following simple code snippet 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);
}
}
}
Just one question about this code here. It works exactly as expected but I can not reduce the length of the string Good Day !!. If an attempt is made to do so, it causes a java.lang.ArrayIndexOutOfBoudsException
. If the length is increased, the program runs well but the rest of the characters in the displaying string are truncated means that the length of the both of the strings should somewhat be the same. Why? This is the thing that I couldn't understand.
The value
field is a char[]
which internally stores the character array that the string uses as its backing store. Other fields indicate the initial offset into the character array, and the length of the string. (So to take a substring, it just creates a new String
object which refers to the same char[]
but with a different starting offset and length.)
If you modify those fields as well, you can do pretty much whatever you like with the string. Sample:
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With