title: How to prevent access via reflection?
body: <p>In Java docs it mentioned that using <code>f.setAccessible(true)</code> method we can violate the principal of encapsulation.</p>
  
  <p>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?</p>
  
  <p>For example I have a class with full secured instance variable:</p>
  
  <pre><code>public final class Immutable {
      private final int someVal;
  
      public Immutable(int someVal) {
          this.someVal = someVal;
      }
  
      public int getVal() {
          return someVal;
      }
  }
  </code></pre>
  
  <p>But I can modify that instance variable using reflection like this:</p>
  
  <pre><code>public class Tester {
      public static void main(String[] args)
              throws NoSuchFieldException, SecurityException,
              IllegalArgumentException, IllegalAccessException {
  
          Immutable i = new Immutable(10);
  
          // output 10
          System.out.println(i.getVal());
  
          Field f = i.getClass().getDeclaredField("someVal");
          f.setAccessible(true);
          f.set(i, 11);
  
          // output is 11 which implies some value modified
          System.out.println(i.getVal());
      }
  }
  </code></pre>
  
  <p>In my code, how can I prevent an immutable class being changed with reflection?</p>