首页 > 解决方案 > 在 Java 9 或 10 中创建 FXML 成员的正确方法是什么?

问题描述

升级到 Java 10(从 8 开始)后,出现以下错误:

InaccessibleObjectException: Unable to make field private javafx.scene.control.Button tech.flexpoint.dashman.controllers.configurator.RegistrationController.registerButton accessible: module tech.flexpoint.dashman does not "opens tech.flexpoint.dashman.controllers.configurator" to module javafx.fxml

这是否意味着我应该公开它们?这是否使@FXML注解在 Java 9 和 10 中基本上无用?

标签: javafxfxmljava-9java-10java-module

解决方案


由于您使用的是模块,因此默认情况下不允许反射访问您的类的私有成员。异常基本上告诉你需要做什么:

module tech.flexpoint.dashman {
    ...

    // allow everyone to access classes in tech.flexpoint.dashman.controllers.configurator via reflection
    opens tech.flexpoint.dashman.controllers.configurator;
}

或者

module tech.flexpoint.dashman {
    ...

    // allow only module javafx.fxml access classes in tech.flexpoint.dashman.controllers.configurator via reflection
    opens tech.flexpoint.dashman.controllers.configurator to javafx.fxml;
}

这并没有什么@FXML用处。仍然需要标记允许使用的非public成员,FXMLLoader只需要明确声明允许反射覆盖对成员的访问。(FXMLLoader使用反射,所以至少javafx.fxml模块需要这种访问才能使注入工作。)

根据包的内容,将控制器移动到它自己的子包以不允许反射访问非控制器类可能是有益的。


推荐阅读