user1016403
user1016403

Reputation: 12621

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?

Upvotes: 8

Views: 906

Answers (4)

user949300
user949300

Reputation: 15729

I'm no expert on the java Security stuff, but I think you have to provide your own SecurityManager and override checkMemberAccess(). e.g., 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.

Upvotes: 0

Wayne
Wayne

Reputation: 60414

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.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

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.

Upvotes: 8

blank
blank

Reputation: 18170

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

Upvotes: 2

Related Questions