java - 内部类甚至可以访问外部类的私有(private)成员..这不是侵犯隐私吗?

标签 java

我的面试官问了我关于内部类的问题。在向他解释了一切之后,他用一句话阻止了我——如果内部类可以访问外部类的私有(private)成员,那么这不是侵犯隐私吗? 我无法回答。

最佳答案

从 JVM 的角度来看,是的,内部类访问外部类的私有(private)成员侵犯了隐私。

但是,从 Java 的角度来看,不,它并不侵犯隐私。

JVM 视角

Java 虚拟机规范,第 5.4.4. Access Control 部分说:

A field or method R is accessible to a class or interface D if and only if any of the following is true:

  • [...]

  • R is private and is declared in D.

因此,JVM 只允许同一个类中的代码访问 private 成员,即嵌套类无法访问外部类的 private 成员。

Java 视角

Java 语言规范,第 6.6.1. Determining Accessibility 部分说:

A member (class, interface, field, or method) of a reference type, or a constructor of a class type, is accessible only if the type is accessible and the member or constructor is declared to permit access:

  • [...]

  • Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

因此,顶级类和/或嵌套类中的 private 成员可以从该顶级类中的任何地方的代码访问。由于嵌套类根据定义出现在封闭的顶级类的主体内,因此嵌套类中的代码可以访问外部类的 private 成员。

综合访问

为了解决这种差异,Java 编译器创建隐藏(合成)方法,以允许密切相关的类之间(即顶级类与其所有嵌套类之间)进行“私有(private)”访问。

这是编译器的内部技巧,并没有真正记录在规范中。 JVMS,部分 4.7.8. The Synthetic Attribute说:

[...] A class member that does not appear in the source code must be marked using a Synthetic attribute, or else it must have its ACC_SYNTHETIC flag set. [...]

The Synthetic attribute was introduced in JDK 1.1 to support nested classes and interfaces.

有关更多信息,请在网络上搜索 java synthetic accessor .

另请参阅:Synthetic accessor method warning

关于java - 内部类甚至可以访问外部类的私有(private)成员..这不是侵犯隐私吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52242363/

相关文章:

java - 将字符串从一个类发送到一个 Activity

java - java中自定义字符串分割方法

java - 如何使用 smack API 从 Google Talk 获取我的头像?

java - 在 Swing 中使用仿射变换将字体大小设置为与其容器成比例

java - 锁在java中是如何工作的

java - 如何使用java只从字符串列表中获取数字

java - 使用流从 HashSet 中排除极值

java - 如何在返回 hashmap 时设置 xml 的父元素

java - "<identifier> expected"Java 编译错误

java - ChangeListener 功能用于检查带有时间延迟/或其他解决方案的键入值