Reflection을 사용한 String Destroyer

Posted by epicdev Archive : 2011. 11. 16. 21:09
출처: http://snippets.dzone.com/posts/show/7920


출력 결과
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.