gpt4 book ai didi

java - 带有 Object[] 参数的 Constructor.newInstance

转载 作者:行者123 更新时间:2023-12-02 03:38:44 30 4
gpt4 key购买 nike

我已经编程 java 很长时间了,由于某种原因,我无法弄清楚为什么这会给我一个参数类型不匹配的问题。我创建了一个非常简单的 JUnit 测试,任何人都可以运行。只需复制并粘贴下面的代码即可。任何帮助将非常感激。谢谢!

    import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.junit.Test;



public class TestObjectArrayConstructor {
@Test
public void testLabelValueObjectArrayConstructor(){
Constructor constructor = null;
try {
constructor = LabelValue.class.getConstructor(
new Class[]{Object[].class});
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Object[] array = new Object[]{"Doll"};
Object labelValue = null;
try {
labelValue = constructor.newInstance(array);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("don");
}
}



public class LabelValue {
private String label;
private String value;

public LabelValue(){

}

public LabelValue(Object[] array)
{
if(array != null && array.length > 0)
{
this.label = (String)array[0];
this.value = (String)array[0];
}
}


public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

最佳答案

试试这个(未测试):

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

因为 newInstance 需要一个对象数组(不同的参数),而你的情况不明确,因为你的参数是一个对象数组。

关于java - 带有 Object[] 参数的 Constructor.newInstance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37123079/

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