mardi 24 mars 2015

How to prevent access via reflection?

In Java docs it mentioned that using f.setAccessible(true) method we can violate the principal of encapsulation.


But if I am writing any class which has full security, for instance with a private variable, how can I prevent it from being accessed with reflection?


For example I have a class with full secured instance variable:



public final class Immutable {
private final int someVal;

public Immutable(int someVal) {
this.someVal = someVal;
}

public int getVal() {
return someVal;
}
}


But I can modify that instance variable using reflection like this:



public class Tester {
public static void main(String[] args)
throws NoSuchFieldException, SecurityException,
IllegalArgumentException, IllegalAccessException {

Immutable i = new Immutable(10);
System.out.println(i.getVal()); // output 10
Field f = i.getClass().getDeclaredField("someVal");
f.setAccessible(true);
f.set(i, 11);
System.out.println(i.getVal()); // output is 11 which implies some value modified
}
}


In my code, how can I prevent an immutable class being changed with reflection?






Aucun commentaire:

Enregistrer un commentaire