Over a million developers have joined DZone.

Reflection - String Destroyer

DZone's Guide to

Reflection - String Destroyer

· ·
Free Resource
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.set("Hello World", "Java World!".toCharArray());
		System.out.println("Hello World");

Program Output:
Java World!

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.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}