曾经爱过的人 2016-03-21 10:41 采纳率: 0%
浏览 3856

java 反射 java.lang.IllegalArgumentException

package cn.com.reflect;

public class Person {

private String name;
private int age;

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public Person(int age) {
    super();
    this.age = age;
}
public Person(String name) {
    super();
    this.name = name;
}
public Person() {
    super();
}
public Person(String name, int age) {
    super();
    this.name = name;
    this.age = age;
}

}

package cn.com.reflect;

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

public class ReflectDemo4 {

public static void main(String[] args) {

    Class<?> clazz = null;
    try {
        clazz = Class.forName("cn.com.reflect.Person");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Person demo1 = null;
    Constructor<?>[] con = clazz.getConstructors();
    try {
        demo1 = (Person) con[0].newInstance(12);
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

    System.out.println(demo1.getAge());
}

}
java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at cn.com.reflect.ReflectDemo4.main(ReflectDemo4.java:20)
Exception in thread "main" java.lang.NullPointerException
at cn.com.reflect.ReflectDemo4.main(ReflectDemo4.java:31)

  • 写回答

3条回答 默认 最新

  • snailplus 2016-03-21 13:41
    关注

    通过clazz.getConstructors()所获得的构造器的顺序,不一定是书写顺序。很可能是按参数从少到多排列的(未查证)。
    你的con[0]获得的应该是个默认构造器,所以报错。你可以通过con[0]的getParameterTypes()来获得参数的个数,类型等信息进行判断,
    进而确定要使用的构造器。
    或者,干脆通过带参数的clazz.getConstructors(xxx,yyy。。。)函数,来明确获得一个你指定的参数列表的构造器。

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算