简体   繁体   English

从匿名类访问阴影变量

[英]Access shadowed variable from anonymous class

I have a static function that takes a parameter called X. 我有一个静态函数,它接受一个名为X的参数。

In this static function I create an anonymous class. 在这个静态函数中,我创建了一个匿名类。 This class should have a member variable, also called X. 这个类应该有一个成员变量,也称为X.

From the functions in the anonymous class, how can I access the function's parameter X? 从匿名类中的函数,我如何访问函数的参数X?

To illustrate: 为了显示:

class Test {

    static void func(final List<T> X) {

        new Test() {
            final T[] X = ?.X.toArray();
        };
    }
}

In my real code I want to create an array in my anonymous class from a list argument (via toArray() in the anonymous class's initialisation), and I want to re-use the same variable name rather than using hungarian notation to differentiate them. 在我的真实代码中,我想从list参数(通过匿名类的初始化中的toArray()在我的匿名类中创建一个数组,并且我想重用相同的变量名而不是使用匈牙利符号来区分它们。

This isn't possible in Java. 这在Java中是不可能的。 Function parameters have no "namespace" like this which you could use to denote which variable you mean. 函数参数没有像this “命名空间”,您可以用它来表示您的意思。

The only solution is to create an arbitrary prefix like outerX for the outer parameter or xAsArray for the inner. 唯一的解决方案是为外部参数创建一个像outerX的任意前缀,或者为内部创建一个xAsArray

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

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