是否可以通过某种方式限定最终参数以解决与匿名类成员的命名冲突? [英] Can final parameters be qualified in some way to resolve naming conflicts with anonymous class members?

查看:127
本文介绍了是否可以通过某种方式限定最终参数以解决与匿名类成员的命名冲突?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你为什么要这样做,这对你有什么不妥?尽管如此,有没有办法在不更改最终方法参数名的情况下完成此操作?

"Why are you doing this what is wrong with you?" notwithstanding, is there any way to accomplish this without changing the final method parameter name?

private Foo createAnonymousFoo(final Bar bar) {
    return new Foo() {
        private Bar bar = SomeUnknownScopeQualifier.bar;

        public Bar getBar() {
            return bar;
        }

        public void doSomethingThatReassignsBar() {
            bar = bar.createSomeDerivedInstanceOfBar();
        }
    };
}

显然没有doSomethingThatReassignsBar调用,你不需要成员Bar等等上。在这种情况下,简单的解决方法是将最终栏栏更改为 final bar startBar ,然后分配是精细。但出于好奇,是否可以专门引用最终栏(类似于你所说的 Super.this )?

Obviously without the doSomethingThatReassignsBar call, you wouldn't need the member Bar and so on. In this case, the simple fix is to change final Bar bar to something like final Bar startBar and then the assignment is fine. But out of curiosity, is it possible to specifically refer to the final Bar (Similar to the way you would say Super.this)?

推荐答案

我认为你的问题的答案是不。来自 Java语言规范

I think the answer to your question is "no". From the Java Language Specification:


局部变量(§14.4),形式参数(§8.4.1),异常参数(§14.20)和本地类(§14.3)只能使用简单的名称(§6.2),而不是限定名称(§6.6)。

A local variable (§14.4), formal parameter (§8.4.1), exception parameter (§14.20), and local class (§14.3) can only be referred to using a simple name (§6.2), not a qualified name (§6.6).

换句话说,在示例代码中没有任何东西可以替换 SomeUnknownScopeQualifier ,以使内部类中的赋值语句引用形式参数名称。

In other words, there's nothing you can replace SomeUnknownScopeQualifier with in your example code to make the assignment statement in the inner class refer to the formal parameter name.

这篇关于是否可以通过某种方式限定最终参数以解决与匿名类成员的命名冲突?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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