Variable visibility inside anonymous class method
I have a开发者_JAVA技巧 problem with XMLTool java library. Let's consider following code:
private void parse() {
List<String> list = new ArrayList<String>();
doc.gotoChild("Body")
.gotoChild("ExternalListOfCodes")
.forEachChild(new CallBack() {
public void execute(XMLTag doc) {
if (doc.getCurrentTagName().equalsIgnoreCase("UnitOfMeasure")){
//Here's the problem!
list.add(
doc.gotoChild("UnitOfMeasureCode").getInnerText()
);
}
}
}
}
There's a loop forEachChild
and what I'd like to achieve is to add tag content to a list. Certainly, it's not possible because variable list
is not visible there.
Any ideas how to solve it? Thanks for any help!
It is visible, you just need to make it final
:
final List<String> list = new ArrayList<String>();
More generally, an anonymous class (like your CallBack
) can only access local variables external to the class if those variables are declared final
.
精彩评论