9

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

Doug Moscrop
  • 4,479
  • 3
  • 26
  • 46
  • 6
    "Why are you doing this what is wrong with you?" :) – jpm Apr 13 '12 at 16:36
  • It's actually not as reprehensible as you might imagine. I'd created a document builder and was using the visitor pattern to write items, and in the case of a spreadsheet I was simply iterating over cells starting at a "startCell" (the final method param) and moving through them with `cell = cell.nextCell()`, where cell was the ItemVisitor's current cell to write to. – Doug Moscrop Apr 13 '12 at 17:06

2 Answers2

7

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.

Alex
  • 13,811
  • 1
  • 37
  • 50
3

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;

    // ...
  };
}
Jordão
  • 55,340
  • 13
  • 112
  • 144
  • This seems no different than just naming the method parameter `alias`? – Doug Moscrop Apr 13 '12 at 17:02
  • 2
    The method parameter name might be available to code completion tools or the like. Thus, it's better to have the self-documenting name in the public API and use a distinct (though possibly cryptic) name internally. – jpm Apr 13 '12 at 17:08
  • That's a great point. I've upvoted this as it is a useful and insightful answer. The answer from Alex, however, cites the JLS and I feel I should accept that one. – Doug Moscrop Apr 13 '12 at 17:17