What are some crazy snippets of code that you've seen?
Java string pool coupled with reflection can produce some unimaginable result in Java:
- import java.lang.reflect.Field;
- class MessingWithString {
- public static void main (String[] args) {
- String str = "Mario";
- toLuigi(str);
- System.out.println(str + " " + "Mario");
- }
- public static void toLuigi(String original) {
- try {
- Field stringValue = String.class.getDeclaredField("value");
- stringValue.setAccessible(true);
- stringValue.set(original, "Luigi".toCharArray());
- } catch (Exception ex) {
- // 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
- String str1 = "string";
- String str2 = "string";
- 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"
Articoli simili
- What mobile games do you play daily and what keeps you coming back. If you could improve the game, what would you add?
- What one movie scene is still riveting for you, even though you've seen it dozens of times?
- Do you watch anime and if so, which anime do you watch (sorry if you answered this already I'm new to Quora)?
- Can someone list some sci-fi shows I've seen a lot? It doesn't have to be sci-Fi, just action is good enough.