Fun things you can do by mutating Java strings
- by polygenelubricants
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.