从内部匿名类引用匿名类的外部实例

时间:2016-11-15 08:19:02

标签: java anonymous-inner-class

在以下代码段中:

public void main(){
    //Enclosing scope
    final TextField field = new TextField("", uiSkin) {
        @Override
        protected InputListener createInputListener() {
            return new TextFieldClickListener() {
                @Override
                public boolean keyUp(com.badlogic.gdx.scenes.scene2d.InputEvent event, int keycode) {



                    // error1 => The local variable field may not have been initialized
                    System.out.println("Field "+field+"event="+event+" key={}"+keycode);

                    // error2 => No enclosing instance of the type TextField is accessible in scope
                    System.out.println("Field "+TextField.this+"event="+event+" key={}"+keycode);



                    return super.keyUp(event, keycode);
                };
            };
        }
    };
}

有没有办法从内部匿名类中引用匿名类的外部实例?

第二个错误出现在我在Keyword for the outer class from an anonymous inner class找到的解决方案上。似乎问题共享一些概念和问题空间,但性质不同。

1 个答案:

答案 0 :(得分:0)

可以通过定义一个新字段来修复问题,该字段捕获对封闭的引用。

//Enclosing scope
final TextField field = new TextField("", uiSkin) {
    TextField this2 = this;
    @Override
    protected InputListener createInputListener() {
        return new TextFieldClickListener() {
            @Override
            public boolean keyUp(com.badlogic.gdx.scenes.scene2d.InputEvent event, int keycode) {
                System.out.println("Field "+this2+"event="+event+" key={}"+keycode);
                return super.keyUp(event, keycode);
            };
        };
    }
};