How to limit a variable to inaccessibility outside a class in java?

I am using java. I know using private access modifier, which we can limit. But using the Reflection API , I can access the variable outside the class. Then what is the private modifier used in here?

+7
source share
4 answers

Because reflection destroys encapsulation. You can prevent the use of reflection api if the application runs in a security-managed environment. See Java Security Manager

+2
source

private prevents access to it from other classes using Java. However, using JNI or the library, you can do something differently. You can prevent reflection with a security manager, but this is rarely required.

Note. Some libraries, such as Serialization, must have access to private fields in order to work.

+8
source

what a private modifier uses here

The private modifier is not a security mechanism; this is (one part) the encapsulation mechanism. Hiding the internal objects of an object from public consumption helps to keep the objects in a consistent and usable state by providing comments on which parts of the object make up an open interface (and you can rely on them to not change).

Of course, users can use reflection to access data in private fields, but they will know that they are doing what is not supported by the library.

+1
source

I am not a Java security expert, but I think you should provide your own SecurityManager and override checkMemberAccess (). for example, to prevent all reflection

  public void checkMemberAccess(Class<?> clazz, int which) throws AccessControlException { if (which != Member.PUBLIC) { throw new AccessControlException("No reflection on non-public fields allowed"); } } 

Obviously, in the real world, you can only check a specific subset of the β€œimportant” classes in the first argument. And, as noted in many other answers, this will cause problems for many third-party libraries.

0
source

All Articles