gpt4 book ai didi

java - 将类名作为参数传递

转载 作者:行者123 更新时间:2023-12-02 02:55:56 25 4
gpt4 key购买 nike

我有以下功能

public void loadWindowAndSendDataTest(String path, String appName, ConnectionData connectionData) {
try {
Stage subWindow = new Stage();
subWindow.initModality(Modality.APPLICATION_MODAL);
FXMLLoader loader = new FXMLLoader();
Parent parent = loader.load(getClass().getResource(path).openStream());
ExitController exitController = (ExitController) loader.getController();
exitController.getConnectionData(connectionData);

Scene scene = new Scene(parent);

subWindow.setScene(scene);
subWindow.setTitle(appName);
subWindow.show();
} catch(IOException e) {
e.printStackTrace();
}

我想要实现的是拥有更通用的功能,我可以在其中传递类名(在本例中为 ExitController),所以它需要这样的东西:

public void loadWindowAndSendDataTest(String path, String appName, ConnectionData connectionData, String className) {
try {
Stage subWindow = new Stage();
subWindow.initModality(Modality.APPLICATION_MODAL);
FXMLLoader loader = new FXMLLoader();
Parent parent = loader.load(getClass().getResource(path).openStream());
/* do sth with className to obtain UsedClassController class */
UsedClassController usedClassController = (UsedClassController) loader.getController();
usedClassControler.getConnectionData(connectionData);

Scene scene = new Scene(parent);

subWindow.setScene(scene);
subWindow.setTitle(appName);
subWindow.show();
} catch(IOException e) {
e.printStackTrace();
}

假设我传递给这个函数的类有 getConnectionData()功能已实现。有办法做到这一点吗?

最佳答案

您应该使用方法 getConnectionData() 创建一个接口(interface),并在您的 UsedClassController 类中实现此接口(interface)。

要获取类的名称,请尝试从类对象中使用getSimpleName()。 BigDecimal 示例:

 BigDecimal.class.getSimpleName();

将返回BigDecimal。如果你想获取带有包的名称,可以使用getCanonicalName()

关于java - 将类名作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43068598/

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