大家看看,老是报java.lang.IllegalArgumentException: argument type mismatch错,求大神解解
说明:我是用有参构造器来反射的,就不要对我说用无参的了
package Tcon.net.bean;
public class Person {
private String name ="花花";
private int age =12;
// public Person(){
// super();
// System.out.println("空参数构造器");
// }
public Person(String namel,int age){
super();
this.name = name;
this.age = age;
}
}
//------------------------------
package Tcon.net.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
test02();
}
public static void test01() throws ClassNotFoundException, InstantiationException, IllegalAccessException{
String str = "Tcon.net.bean.Person";
Class forName=Class.forName(str);
//有无惨的构造器
Object obj = forName.newInstance();
}
public static void test02() throws NoSuchMethodException, SecurityException, ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
String str = "Tcon.net.bean.Person";
Class forName=Class.forName(str);
//没有,无惨的构造器
Class[] arg0 = {String.class,int.class};
Constructor cons =forName.getConstructor(arg0);
Object[] initargs = {"小明","44"};
Object ss = cons.newInstance(initargs);
System.out.println(ss);
}
}
运行后报错:
Exception in thread "main" java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at Tcon.net.util.Test.test02(Test.java:25)
at Tcon.net.util.Test.main(Test.java:8)
求解释,
------解决方案--------------------
原因:你的参数类型错误。
构造函数接收的参数是String,int。而你传入的参数是String,String。类型不匹配。所以报此错误。只要将“44”改为44即可。
给分,谢谢!