先上源码
package com.NonsenceNumberOne;import java.lang.reflect.Constructor;public class ReflectDemo {
public static void main(String[] args) {
Class<?> demo=null;
try{
demo=Class.forName("com.NonsenceNumberOne.Person1");
}catch (Exception e) {
e.printStackTrace();
}
Person1 per1=null;
Person1 per2=null;
Person1 per3=null;
Person1 per4=null;

Constructor<?> cons[]=demo.getConstructors();
try{
                        //这里会报错
             /*per1=(Person1)cons[0].newInstance();
per2=(Person1)cons[1].newInstance("songnan");
per3=(Person1)cons[3].newInstance("songnan",10);
per4=(Person1)cons[2].newInstance(20);*/

                        //这里不报错
per1=(Person1)cons[0].newInstance("songnan");
per2=(Person1)cons[1].newInstance(20);
per3=(Person1)cons[3].newInstance();
per4=(Person1)cons[2].newInstance("songnan",20);

}catch(Exception e){
e.printStackTrace();
}
System.out.println(per1);
System.out.println(per2);
System.out.println(per3);
System.out.println(per4);



}


}class Person1{

public Person1(){
System.out.println("wwwwww");
}
public Person1(String name){
this.name = name;
}
public Person1(int age){
this.age = age;
}
public Person1(String name,int age){
this.age = age;
this.name = name;
}
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;  
    }  
    @Override  
    public String toString(){  
        return "["+this.name+"  "+this.age+"]";  
    }  
    private String name;  
    private int age;
}
这个构造函数的顺序不是我在代码中写的顺序,请问是大神这是为什么?

解决方案 »

  1.   

    public Constructor<?>[] getDeclaredConstructors()
                                             throws SecurityException
    Returns an array of Constructor objects reflecting all the constructors declared by the class represented by this Class object. These are public, protected, default (package) access, and private constructors. The elements in the array returned are not sorted and are not in any particular order. If the class has a default constructor, it is included in the returned array. This method returns an array of length 0 if this Class object represents an interface, a primitive type, an array class, or void. 
    See The Java Language Specification, section 8.2. 
    这是源码里对getDeclaredConstructors的说明,getConstructors()的没看到有说,不过代码没有直接表明是按某特定顺序返回的,所以我觉得应该也和getDeclaredConstructors差不多吧。