Fun things you can do by mutating Java strings
        Posted  
        
            by polygenelubricants
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by polygenelubricants
        
        
        
        Published on 2010-03-24T07:27:49Z
        Indexed on 
            2010/03/24
            7:33 UTC
        
        
        Read the original article
        Hit count: 422
        
So I've come around since I asked how to limit setAccessible to only “legitimate” uses and have come to embrace its power for fun. Enabled by its power, of course, is string mutation.
import java.lang.reflect.Field;
public class Mutator {
   static void mutate(Object obj, String field, Object newValue) {
      try {
         Field f = obj.getClass().getDeclaredField(field);
         f.setAccessible(true);
         f.set(obj, newValue);      
      } catch (Exception e) {
      }
   }
   public static void mutate(String from, String to) {
      mutate(from, "value", to.toCharArray());
      mutate(from, "count", to.length());
   }
   public static void main(String args[]) {
      Mutator.mutate(System.getProperty("line.separator"), "<br/>\n");
      System.out.println("Hello world!");
      Mutator.mutate(Integer.toString(Integer.MIN_VALUE), "OMG!");
      System.out.println(-2147483648);
      Mutator.mutate(String.valueOf((Object) null), "LOL!");
      System.out.println(Arrays.toString(new int[3][]));
      Mutator.mutate(Arrays.toString(new int[0]), ":(");
      System.out.println(Arrays.toString(new byte[0]));
   }   
}
Output (if no exception is thrown):
Hello world!<br/>
OMG!<br/>
[LOL!, LOL!, LOL!]<br/>
:(<br/>
Let's see what other fun things we can come up with.
© Stack Overflow or respective owner