简体   繁体   English

如何限制变量不要在java中的类外访问?

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

I am using java. 我正在使用java。 I know by using private access modifier we can restrict. 我知道通过使用私有访问修饰符我们可以限制。 But using Reflection API still I can access the variable outside the class. 但是使用Reflection API仍然可以访问类外的变量。 Then what is the use of private modifier here? 那么私有修饰符在这里有什么用?

private prevents you accessing it from other classes using Java. private阻止您使用Java从其他类访问它。 However using JNI or a library you can do things differently. 但是,使用JNI或库可以做不同的事情。 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. 注意:像Serialization这样的库需要能够访问私有字段才能工作。

Because reflection breaks encapsulation. 因为反射破坏了封装。 You can prevent the use of the reflection api if your application is running in a security managed environment. 如果应用程序在安全托管环境中运行,则可以阻止使用反射API。 See Java Security Manager 请参阅Java安全管理器

then what is the use of private modifier here 那么私有修饰符在这里有什么用处

The private modifier is not a security mechanism; private修饰符不是安全机制; 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. 当然,用户可以使用反射来访问private字段中的数据,但他们知道他们正在做一些不受库支持的事情。

I'm no expert on the java Security stuff, but I think you have to provide your own SecurityManager and override checkMemberAccess(). 我不是java安全的专家,但我认为你必须提供自己的SecurityManager并覆盖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. 而且,正如许多其他回复中所述,这将导致许多第三方库出现问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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