DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Reflection - String Destroyer

09.16.2009
| 3574 views |
  • submit to reddit
        The first program in almost all programming languages is a "Hello World" program. What if the program prints something else. Here is how we can 'hack' the Hello Worlds using Reflection!!

import java.lang.reflect.Field;

public class StringDestroyer {
	public static void main(String[] args)
	throws IllegalAccessException, NoSuchFieldException {
		Field value = String.class.getDeclaredField("value");
		value.setAccessible(true);
		value.set("Hello World", "Java World!".toCharArray());
		System.out.println("Hello World");
	}
}

<b>Program Output</b>:
Java World!

Note:
The original string ("Hello World") should be smaller or equal in size when compared to the new string ("Java World!") or else you will end up in ArrayIndexOufofBoundsException.

If the original string is smaller than the new string, then the new string will be truncated. In the above code if i use 'value.set("Hello World", "Java World$Rocks!".toCharArray());' then the output is 'Java World$'

If the original string is larger than the new string then you will end up in ArrayIndexOutOfBoundsException
Stack trace below:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
	at java.lang.System.arraycopy(Native Method)
	at java.lang.String.getChars(Unknown Source)
	at java.io.BufferedWriter.write(Unknown Source)
	at java.io.Writer.write(Unknown Source)
	at java.io.PrintStream.write(Unknown Source)
	at java.io.PrintStream.print(Unknown Source)
	at java.io.PrintStream.println(Unknown Source)
	at com.test.reflection.StringDestroyer.main(StringDestroyer.java:16)

I digged into String.java source code and found that there is a variable int count declared final. Once assigned, the value for count variable cannot be changed. The System.arraycopy(in the above exception) statement uses this count variable for copying the char array to another one.