在对象初始化块内使用花括号

Jyu*_*ace 0 java javafx

为什么bind()仅在将范围大括号内设置时该函数存在?

public void initialize() {

    inputsAreFull = new BooleanBinding() {
        {
            bind();
        }

        @Override
        protected boolean computeValue() {
            return false;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

IntelliJ会自动建议bind()在花括号内使用,但是在花括号外不存在该功能吗?

这行不通:

public void initialize() {

    inputsAreFull = new BooleanBinding() {

        bind();

        @Override
        protected boolean computeValue() {
            return false;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

chr*_*her 7

您使用的语法是用于声明type实现的快捷方式BooleanBinding。您实际上是在类声明中。

public void initialize(){

    inputsAreFull = new BooleanBinding() {
        // This is equivalent to a class level scope for your anonymous class implementation.
        {
            bind();
        }

        @Override
        protected boolean computeValue() {
            return false;
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

没有初始化程序块,您不能在类级别随机调用方法。您可以通过编写来测试...

class MyClass extends BooleanBinding {
    bind(); // It's not gonna be very happy with you.

    @Override
    protected boolean computeValue() {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

具有运行示例的IDEOne:http ://ideone.com/EERkXB

另请参见什么是初始化块?

  • 那不是静态初始化程序块,而是实例初始化程序块 (2认同)
  • 我认为可以通过定义/解释初始化程序块与ctor相比的工作方式以及为什么在这种情况下必须使用一个来定义/解释,从而增强此答案。 (2认同)

Joo*_*gen 5

new BooleanBinding() { ... }引入了的匿名子类BooleanBinding

现在bind受保护的方法,因此不允许这样做inputsAreFull.bind()

但是可以{ ... }在子类主体中的匿名初始化程序块中调用bind 。

还有一点需要注意:由于此时对象尚未完全初始化;如果实际上是在BooleanBinding构造函数中执行的代码(由编译器负责),则该方法bind不应是可重写的。为此,可以使用private或(在这里)一种protected final方法。