带Object []参数的Constructor.newInstance

时间:2016-05-09 18:38:15

标签: java

我一直在编程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;
    }
}

2 个答案:

答案 0 :(得分:2)

试试这个(未经测试):

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

因为newInstance需要一个Object数组(不同的args),并且你的情况不明确,因为你的param是一个Object数组。

答案 1 :(得分:0)

当您想要从newInstance创建constructor时,您需要传递实际参数,在您的情况下,单个参数arraynew Object[]: 取代

labelValue = constructor.newInstance(array);

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