求教大神java反射构造函数的问题,求各位大神赏脸

先上源码
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;
}

这个构造函数的顺序不是我在代码中写的顺序,请问是大神这是为什么?
...全文
105 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
谢谢楼上大神。原来底层就是乱的,这下明白了。。
ZZZ5512536 2013-10-21
  • 打赏
  • 举报
回复
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差不多吧。

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧