简体   繁体   English

当嵌套类与封闭类的静态成员共享名称时,访问嵌套类的静态成员?

[英]Access static member of nested class when nested class shares a name with a static member of the enclosing class?

Is there any way to access a static member of a nested class from the enclosing class when the nested class shares a name with a static member of the enclosing class? 当嵌套类与封闭类的静态成员共享名称时,有什么方法可以从封闭类中访问嵌套类的静态成员? For example: 例如:

package a;

class a {
    static Object b;

    static class b {

        static Object foo;
    }

    static Object needAccessToFoo;

    static {
        // can I access foo?
    }

} 

The class b (as opposed to the member b ) can be accessed when being used as a Type via a (or [b.]ba ). b (与成员b相对)在通过a (或[b.]ba )用作Type时可以访问。 And foo can be accessed using the instance of the nested class b as so: 可以使用嵌套类b的实例访问foo

static {
    [a.][a.]b bar = new b();
    needAccessToFoo = bar.foo;
}

However, since b is a nested class and not an inner class , it leaves one to wonder if there is a proper way to statically reference foo without going through an instance of b (the object referred to by bar ). 但是,由于b是一个嵌套类而不是一个内部类 ,因此它使人们想知道是否存在一种适当的方法来静态引用foo而无需通过b的实例(由bar引用的对象)。 Not to mention it's generally accepted as bad practice to access a static member via an object. 更不用说,通过对象访问静态成员通常被认为是不好的做法。

This problem is known as Obscuring. 此问题称为“模糊”。 The JLS states JLS州

A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. 在可能将其解释为变量,类型或包的名称的上下文中,可能会出现一个简单的名称。 In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package. 在这些情况下,第6.5节的规则指定将优先于类型选择变量,并且优先于包选择类型。 Thus, it is may sometimes be impossible to refer to a visible type or package declaration via its simple name. 因此, 有时可能无法通过其简单名称引用可见类型或程序包声明。 We say that such a declaration is obscured. 我们说这样的声明是模糊的。

It won't be possible to access foo . 无法访问foo

In the context of the static initializer block there are two things with the name b . static初始化程序块的上下文中,有两个名称为b东西。 And because of the rule above, the variable will always be chosen when using that conflicting name. 并且由于上述规则,使用该冲突名称时将始终选择该变量。 Qualifying the variable with its enclosing type, ab doesn't change anything because the variable is static and therefore accessible through that reference. 用变量的封闭类型ab不会更改任何内容,因为变量是static ,因此可以通过该引用进行访问。

Yes since everything is static and a is in scope of your static block you can do: 是的,因为一切是静态的, a是在你的范围static块,你可以这样做:

static { Object foo2 = a.foo; // can I access foo? }

You will need to rename your outer class though to prevent a name collision. 您将需要重命名外部类,以防止名称冲突。 Otherwise how will the compiler know which a you are referring to? 否则,编译器怎么会知道这a你是指?

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

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