In Java docs, it was mentioned that using the f.setAccessible(true) method, we can violate the encapsulation principle.
But if I write any class that has complete safety, for example, with a private variable, how can I prevent it from being accessed using reflection?
For example, I have a class with a fully protected 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 change this instance variable using reflection as follows:
public class Tester { public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { Immutable i = new Immutable(10);
In my code, how can I prevent the immutable class from changing with reflection?
source share