简体   繁体   中英

how to restrict the variable not to access outside the class in java?

I am using java. I know by using private access modifier we can restrict. But using Reflection API still I can access the variable outside the class. Then what is the use of private modifier here?

private prevents you accessing it from other classes using Java. However using JNI or a library you can do things differently. You can prevent reflection with a security manager but this is rarely needed.

Note: some libraries like Serialization need to be able to access private fields to work.

Because reflection breaks encapsulation. You can prevent the use of the reflection api if your application is running in a security managed environment. See Java Security Manager

then what is the use of private modifier here

The private modifier is not a security mechanism; it is (one part of) an encapsulation mechanism. Hiding an object's internals from public consumption helps to keep objects in a consistent, usable state, while providing commentary about what parts of an object compose the public interface (and can be relied upon not to change).

Sure, users can use reflection to access the data in private fields, but they'll know they're doing something that isn't supported by the library.

I'm no expert on the java Security stuff, but I think you have to provide your own SecurityManager and override checkMemberAccess(). eg, 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 might want to check for only a certain subset of "important" classes in the first argument. And, as noted in many other responses, this will cause problems for a lot of 3rd party libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM