简体   繁体   English

访问Java中的程序包专用字段

[英]Accessing package-private fields in Java

Poking around Android API sources. 随便看看Android API来源。 There's FileDescriptor with a data member descriptor with no access modifier: 有一个FileDescriptor带有一个没有访问修饰符的数据成员descriptor

int descriptor;

Then there's class FileOutputStream that constructs a new FileDescriptor and assigns to that field: 然后是FileOutputStream类,该类构造一个新的FileDescriptor并将其分配给该字段:

fd = new FileDescriptor();
fd.descriptor = fileSystem.open(...);

How is that compatible with the field access control model of Java? 它与Java的现场访问控制模型如何兼容? I thought package-private fields are not accessible from outside the declaring class, and there's no notion of friendship like in C++. 我认为无法从声明类的外部访问包私有字段,并且没有像C ++这样的友好概念。

Basically, package-private can be accessed at the class and package levels: 基本上,可以在classpackage级别访问package-private:

From the source : 来源

Access Levels
Modifier    Class   Package  Subclass World
public         Y        Y       Y       Y
protected      Y        Y       Y       N
no modifier    Y        Y       N       N
private        Y        N       N       N

a Declaration with no modifier, like 没有修饰符的声明,例如

int descriptor; int描述符;

Are package private, more commonly referred as DEFAULT are accessible within the package and not outside the package. 是包私有的,在包内而不是包外均可访问DEFAULT。 Any class inside the same package can access these but these are not visible outside package. 同一包内的任何类都可以访问它们,但在包外不可见。

For more details please refer here 有关更多详细信息,请参阅此处

Access Levels
Modifier        Class   Package     Subclass    World
public            Y         Y        Y            Y
protected         Y         Y          Y          N
no modifier       Y         Y          N          N
private           Y         N          N          N

Package private field (and anything else) are just that: private within their package. 包私有字段(以及其他任何内容)就是:包中的私有字段。 This means that no other class can access the field (or other entity) outside of the scope of the package. 这意味着没有其他类可以访问包范围之外的字段(或其他实体)。 For more specific detail, refer here . 有关更多详细信息,请参见此处

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

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