QNA > W > What Are Some Crazy Snippets Of Code That You've Seen?

What are some crazy snippets of code that you've seen?

Java string pool coupled with reflection can produce some unimaginable result in Java:

  1. import java.lang.reflect.Field; 
  2.  
  3. class MessingWithString { 
  4. public static void main (String[] args) { 
  5. String str = "Mario"; 
  6. toLuigi(str); 
  7. System.out.println(str + " " + "Mario"); 
  8.  
  9. public static void toLuigi(String original) { 
  10. try { 
  11. Field stringValue = String.class.getDeclaredField("value"); 
  12. stringValue.setAccessible(true); 
  13. stringValue.set(original, "Luigi".toCharArray()); 
  14. } catch (Exception ex) { 
  15. // Ignore exceptions 

Above code will print:

Luigi Luigi


No I did not mistype it, not "Luigi Mario" but "Luigi Luigi" will be printed.

Every string literal (strings created using double quotes) in Java are interned, meaning it's placed into a pool of Strings managed by Java VM. Every time a string with same content as interned string is created, Java returns the string literal stored in it's string pool instead of creating a new one.

This means that two string literal with same content points to the same object in memory

  1. String str1 = "string"; 
  2. String str2 = "string"; 
  3. System.out.println(str1 == str2); 

Above code will print "true" since they point to same string object in string pool.

Now if you use reflection to modify that string literal's value from "Mario" to "Luigi", then every string literal "Mario" defined thereafter will have value "Luigi"

Di Babara Hartwell

Una persona ti ha mai detto qualcosa che ti ha fatto ripensare alla tua vita? :: Quale pacchetto di icone usi nel mobile?
Link utili