开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜