Skip to content

Instantly share code, notes, and snippets.

@jomoespe
Last active February 10, 2017 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jomoespe/067d4368d8e3a90b5ab5ecf21914c4a4 to your computer and use it in GitHub Desktop.
Save jomoespe/067d4368d8e3a90b5ab5ecf21914c4a4 to your computer and use it in GitHub Desktop.
Example of access and modify final static (inmutable) fields in Java
import java.lang.reflect.Field;
public final class HackInmutable {
static final class InmutableEmployee {
private final int id;
private final String name;
private final Float salary;
private InmutableEmployee(final int id, final String name, final Float salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
public String name() {
return name;
}
}
public static void main(String...args) {
InmutableEmployee employee = new InmutableEmployee(1, "John Doe", 100f);
System.out.printf("The salary of %1$s is %2$s bitcoins. Salary should be hidden :/\n", employee.name(), giveMe(employee, "salary"));
hackIt(employee, "salary", 50f); // hack it!
System.out.printf("The salary of %1$s now is %2$s bitcoins. WTF! \n", employee.name(), giveMe(employee, "salary"));
}
public static Object giveMe(final Object object, final String attribute) {
try {
Field theInmutableFielfd = object.getClass().getDeclaredField(attribute);
theInmutableFielfd.setAccessible(true);
return theInmutableFielfd.get(object);
} catch (NoSuchFieldException |
IllegalArgumentException |
IllegalAccessException e) {
return null;
}
}
public static void hackIt(final Object object, final String attribute, final Object newValue) {
try {
Field theInmutableFielfd = object.getClass().getDeclaredField(attribute);
theInmutableFielfd.setAccessible(true);
theInmutableFielfd.set(object, newValue);
} catch (NoSuchFieldException |
IllegalArgumentException |
IllegalAccessException e) {}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment