Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.