gpt4 book ai didi

java - 如何编写一个接受类类型作为参数的方法,并使用它来转换一些对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:57:55 24 4
gpt4 key购买 nike

我正在使用 JavaFX 8 开发一个 Java 8 桌面应用程序。
我在 MainApp 类 (扩展 Application 类的那个) 中有这个方法。

public void showUserLayout() {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource("view/userLayout.fxml"));
AnchorPane userPane = (AnchorPane) loader.load();

rootAnchorPane.getChildren().clear();
rootAnchorPane.getChildren().add(userPane);

userLayoutController controller = loader.getController();
controller.setMainApp(this);
} catch (IOException e) {
// Handle Exception
}
}

并且我对要加载的每个布局使用相同的代码。

有没有办法创建一个接受类类型作为参数并完成完全相同的工作的方法,例如:

public void genericLayoutLoader(String fxmlFilename, Class rootFXMLElement, Class fxmlController) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource(fxmlFilename));
// Not sure for the Object below
Object chooseUserAndInterval = (rootFXMLElement) loader.load();
// rootAnchorPane is same for every layout
rootAnchorPane.getChildren().clear();
rootAnchorPane.getChildren().add((rootFXMLElement) chooseUserAndInterval);

Object controller = (fxmlController) loader.getController();
((fxmlController)controller).setMainApp(this);
} catch (IOException e) {
// Handle Exception
}
}

我会这样使用它:

public void showUserLayout() {
genericLayoutLoader("view/userLayout.fxml", AnchorPane, userLayoutController);
}

有什么办法可以实现这种行为吗?

最佳答案

如果你想坚持使用类作为参数,你的代码应该看起来像这样:

    public void genericLayoutLoader(String fxmlFilename, Class rootFXMLElement, Class fxmlController) {
try {
FXMLLoader loader = new FXMLLoader();
loader.setLocation(MainApp.class.getResource(fxmlFilename));
// Not sure for the Object below
Object chooseUserAndInterval = loader.load();
// rootAnchorPane is same for every layout
rootAnchorPane.getChildren().clear();
rootAnchorPane.getChildren().add(chooseUserAndInterval);

Object controller = loader.getController();
fxmlController.getMethod("setMainApp", new Class[] { MainApp.class }).invoke(controller, this);
} catch (IOException e) {
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}

public void showUserLayout() {
genericLayoutLoader("view/userLayout.fxml", AnchorPane.class, Controller.class);
}

但是,我仍然建议尽可能使用接口(interface)来解决这个问题。

关于java - 如何编写一个接受类类型作为参数的方法,并使用它来转换一些对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32181957/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com