私有嵌套类的可访问性

发布于 2024-12-05 08:52:23 字数 233 浏览 1 评论 0原文

我有一个类似

@SomeAnnotation(Outer.Inner.class)
enum Outer {
    A, B, C;
    private static class Inner {...}
}

在 Eclipse 中工作正常的类,但是 javac 抱怨私有访问。哪个编译器是正确的?

据我所知,只要访问发生在同一个源文件中,所有访问限制都会被忽略。

I have a class like

@SomeAnnotation(Outer.Inner.class)
enum Outer {
    A, B, C;
    private static class Inner {...}
}

which works fine in Eclipse, but javac complains about private access. Which compiler is right?

According to what I know, all access restrictions get ignored as long as the access occurs in the same source file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

墨离汐 2024-12-12 08:52:23

类声明中的可访问性与类内部的可访问性不同 - 声明中的任何符号都不能引用私有成员。这是因为声明给出的信息本质上必须至少可供包的其余部分使用。

例如,考虑一个包私有类 Outer

class Outer<T extends Outer.Inner> {

   private static class Inner { }
}

上述内容无效,因为包的其他成员无法访问 Inner,即使它们必须能够访问Outer 并通过其声明了解它是什么。类似的逻辑可以应用于您的情况。

我不确定为什么 Eclipse 允许这样做,但我想说 javac 是正确的,并且 NetBeans 似乎也同意。

Accessibility in the class declaration is different than from within the class - no symbols in the declaration can refer to private members. This is because the information given by the declaration must inherently be available to at least the rest of the package.

For example, consider a package-private class Outer:

class Outer<T extends Outer.Inner> {

   private static class Inner { }
}

The above is invalid because other members of the package would not have access to Inner, even though they must be able to access Outer and know what it is via its declaration. Similar logic can be applied to your situation.

I'm not sure why Eclipse allowed it, but I would say javac is correct and NetBeans seems to agree.

著墨染雨君画夕 2024-12-12 08:52:23

我记得一些模糊的安全事件是由同一源文件中所有内容的工作机制引起的。

它完全有可能不再适用于较新版本的 java。

I recall some vague security incident resulting from the mechanism by which all within the same source file works.

It's entirely possible that it no longer works in newer versions of java.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文