What's the correct to make FXML members in Jav

2020-02-12 07:06发布

问题:

After upgrading to Java 10 (from 8), I'm getting these errors:

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

Does it mean I should make them public? Does that make the @FXML annotation essentially useless in Java 9 and 10?

回答1:

Since you're using a module, reflection is not allowed to access private members of your classes by default. The exception basically tells you what needs to be done:

module tech.flexpoint.dashman {
    ...

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

or

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;
}

This does not make @FXML useless. It's still needed to mark non-public members that FXMLLoader is allowed to use, it's just required to explicitly state that reflection is allowed to override access to members. (FXMLLoader uses reflection so at least the javafx.fxml module needs this kind of access for injection to work.)

Depending on the contents of your package it could be beneficial to move the controller(s) to it's own subpackage to not allow reflective access to non-controller classes.