反射报错java.lang.IllegalArgumentException: wrong number of arguments
class Person{ private String name ; private String sex ; public Person(){ System.out.println("c");} public Person(String c1){ this.name =c1; System.out.println("c1"+c1);} public Person(String c1,String c2){ this.name =c1; this.sex =c2; System.out.println("c1"+c1 +"c2"+c2);}</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getName() { </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> name; } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setName(String name) { </span><span style="color: rgba(0, 0, 255, 1)">this</span>.name =<span style="color: rgba(0, 0, 0, 1)"> name; } </span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getSex() { </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sex; } </span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setSex(String sex) { </span><span style="color: rgba(0, 0, 255, 1)">this</span>.sex =<span style="color: rgba(0, 0, 0, 1)"> sex; }
}
public static void main(String [] args){ try { Class<?> clazz = Class.forName("com.leeeason.miaosha.Person") ; // 取得 Class 对象 Constructor<?>[] constructors = clazz.getConstructors(); System.out.print(constructors.length); Object o = constructors[0].newInstance();} catch (Exception e) {e.printStackTrace(); }}</span></pre>
报错 java.lang.IllegalArgumentException: wrong number of arguments
因为构造函数取值的时候是从下往上 从 0 开始
public static void main(String [] args){ try { Class<?> clazz = Class.forName("com.leeeason.miaosha.Person") ; // 取得 Class 对象 Constructor<?>[] constructors = clazz.getConstructors(); //System.out.print(constructors.length); //修改后 Object o = constructors[2].newInstance();} catch (Exception e) {e.printStackTrace(); }}</span></pre>
返回成功