从匿名类访问阴影变量 [英] Access shadowed variable from anonymous class

查看:263
本文介绍了从匿名类访问阴影变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态函数,它接受一个名为X的参数。

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?

为了说明:

class Test {

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

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

在我的真实代码中,我想创建一个数组来自list参数的匿名类(在匿名类的初始化中通过 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.

推荐答案

这在Java中是不可能的。函数参数没有命名空间,如这个,您可以用它来表示您的意思。

This isn't possible in Java. Function parameters have no "namespace" like this which you could use to denote which variable you mean.

唯一解决方案是为外部参数创建一个任意前缀,如 outerX ,或者为内部创建 xAsArray

The only solution is to create an arbitrary prefix like outerX for the outer parameter or xAsArray for the inner.

这篇关于从匿名类访问阴影变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆