How to prevent access through reflection?

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); // 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()); } } 

In my code, how can I prevent the immutable class from changing with reflection?

+6
source share
2 answers

The JVM has built-in security mechanisms that allow you to define code restrictions through the Java security policy file. The Java Security Manager uses the Java security policy file to provide a set of permissions granted to classes. Permissions allow the specified classes running in this JVM instance to allow or not allow certain execution operations. If you enable Java Security Manager but do not specify a security policy file, Java Security Manager uses the default security policies defined in the java.security and java.policy files in the $ JAVA_HOME / jre / lib / security directory. The definition of the policy file can be found here http://docs.oracle.com/javase/7/docs/technotes/guides/security/PolicyFiles.html

+5
source

Extend the SecurityManager class and override this method to restrict viewing access.

 @Override public void checkPackageAccess(String pkg){ // don't allow the use of the reflection package if(pkg.equals("java.lang.reflect")){ throw new SecurityException("Reflection is not allowed!"); } } 
0
source

Source: https://habr.com/ru/post/984216/


All Articles