gpt4 book ai didi

Java 在运行时用 String[] stringArray 参数实例化一个类

转载 作者:行者123 更新时间:2023-12-03 23:01:59 25 4
gpt4 key购买 nike

我无法在运行时获取类的具体实现。我在运行时得到类 className 的名称,我想用接受 String 数组的构造函数初始化它。我有以下内容

stringArray = new String[]{"abc", "def"};
Class clazz = Class.forName(className);
Constructor<MyCustomInterface> constructor = null;
MyCustomInterface myCustomObject = null;
constructor = clazz.getDeclaredConstructor(String[].class); // Gives constructor which takes in String[] I assume
myCustomObject = constructor.newInstance(stringArray); // I am providing the same here

在我的自定义界面实现中我有

public class MyClass implements MyCustomInterface{
public MyClass(String args[]) throws Exception{
//My custom constructor
}
}

但我仍然收到一个异常提示,参数数量错误,即使我正在传递一个字符串数组。我对如何进行感到困惑。任何帮助表示赞赏。

最佳答案

Java 中的数组类型是协变的。这意味着 Object[] objectArray = stringArray; 是一个完全有效的语句。

当您调用 constructor.newInstance 时,您的 stringArray 被转换为 Object[],并且您正在尝试调用构造函数两个单独的 String 参数。

您需要将 stringArray 显式包装在 Object[] 中,或者将其转换为 Object 并让 JVM 自动将其包装在一个 Object[] 给你:

constructor.newInstance(new Object[] { stringArray });

constructor.newInstance((Object) stringArray);

关于Java 在运行时用 String[] stringArray 参数实例化一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23849509/

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