java构造函数。具有Object[]参数的newInstance
我已经编写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;
}
}
# 1 楼答案
试试这个(未经测试):
因为newInstance需要一个对象数组(不同的参数),而您的case是不明确的,因为您的param是一个对象数组
# 2 楼答案
当您想从
constructor
创建newInstance
时,需要将实际参数传递给array
作为new Object[]
: 替换与