Fxml控制器注入最终字段 [英] Fxml Controller Inject Final Field

查看:85
本文介绍了Fxml控制器注入最终字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于将映射到fxml控件的fxml控制器类,例如:

For a fxml controller class that would map to an fxml control, such as:

public MyController
{
    @FXML
    private Button button;
}

是否可以将button字段声明为final?如果完成,则Java编译器(javac)将标记有关未初始化该字段的错误.

Is it possible to declare the button field as final? If it was done, the java compiler (javac) would flag an error about that field not being initialized.

可以理解,按钮字段最终将使用@FXML注入进行初始化.尽管,javac并不能完全理解它,甚至不能完全理解它.

It is understood that the button field will be eventually initialized using the @FXML injection. Albeit, javac does not fully understand this, or even how it would be done.

尽管可能不需要最终限定符,但是最好将其与潜在的与可变性相关的错误最小化,尤其是在永远不打算更改的情况下.

Although the final qualifier may not be needed, however, it would be good to enforce to minimise potential mutability related errors, particularly when it is never intended to change.

尽管我不了解fxml如何初始化其组件的复杂性,除了它使用反射.话虽如此,通常对于依赖注入和反射的领域,最终的限定词不能存在于这种领域吗?

Although I do not understand the complexity on how the fxml workings initialize its component, except that it uses reflection. Having said that, and generally for fields that rely on injection and reflection, then the final qualifier cannot exist on such field?

推荐答案

必须至少在类的构造函数中定义一个final字段.使用@FXML注入时,将在使用反射调用该构造函数之后注入/定义字段.因此,您不能将它们定义为final.

A final field must be define at least in the constructor of the class. When using @FXML injection the fields will be injected / defined after that constructor has been called by using reflection. Therefore you can't define them as final.

这篇关于Fxml控制器注入最终字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆