Can final parameters be qualified in some way to resolve naming conflicts with anonymous class members?

我只是一个虾纸丫 提交于 2019-12-10 02:50:09

问题


"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();
        }
    };
}

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)?


回答1:


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

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).

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.




回答2:


I think it's not possible to do that. Rename the involved variables or create an alias:

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

    // ...
  };
}


来源:https://stackoverflow.com/questions/10144789/can-final-parameters-be-qualified-in-some-way-to-resolve-naming-conflicts-with-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!