//创建Tercher模型
public class Tercher{
private String name;
private String homntown;
private double height;
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public String getHometown(){
return homntown;
}
public void setHomntown(String homntown){
this.homntown=homntown;
}
public Teacher(){}
public Teacher(String name,String homntown){
super();
this.name=name;
this.homntown=homntown;
}
public Teacher(String name,double height){
super();
this.name=name;
this.height=height;
}
public String toString(){
return "Teacher[name="+"name"+",homntown="+homntown+",height="+height+"]";
}
}
//主方法
//如果要用反射,先要获取字节码对象
public static void main(String[] args){
//获取字节码对象
Class cls=Teacher.class;
//1.获取无参构造方法,getConstructor()参数可变,根据不同的参数对应不同的构造函数
Constructor c1=cls.getConstructor();
//通过无参构造创建对象,neInstance()参数可变,对应上面的构造方法
Teacher teacher1=(Teacher) c1.neInstance();
System.out.println(teacher1);
//2.创建有参的构造方法,都是String类型的构造方法
Constructor c2=cls.getConstructor(String.class,String.class);
Teacner teacher2=(Teacher)c2.neInstance("szl","十堰");
System.out.println(teacher2);
//3.创建有参构造方法,参数是string和double类型的构造
Constructor c3=cls.getConstructor(String.class,double.class);
Teacner teacher3=(Teacher)c3.neInstance("szl",1.75);
System.out.println(teacher3);
}
反射——通过反射获取带参数的构造方法并使用
最新推荐文章于 2023-10-09 20:38:08 发布