//class反射编程
//定义一个学生类
public class test124 {
public String name;
protected int age;
double height;
private double money;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public test124(String name, Integer age){
this.name=name;
this.age=age;
System.out.println( "调用有参构造方法" );
}
public test124(String name,int age,double money){
this.name=name;
this.age=age;
this.money=money;
}
//看书
public void learn(BookRead book){
System.out.println( "我的名字"+name+ "我正在学习"+book.getName());
}
//奔跑
public void run(){
System.out.println( "我们喜欢奔跑" );
}
}
定义constructor类
import java.lang.reflect.Constructor;
//constructor类反射编程
public class test127{
public static void main(String[] args){
try {
//获取构造器
Class<?> stuCla = Class.forName( "test124" );
//获取构造器反射相关方法实现对象的创建
Constructor cons=stuCla.getConstructor( String.class,Integer.class );
test124 stuObj=(test124)cons.newInstance( "歌谣",23 );
System.out.println( "我的名字是"+stuObj.getName()+"我的年龄"+stuObj.getAge() );
System.out.println( "构造器的访问级别"+cons.getModifiers() );
System.out.println( "参数的个数" +cons.getParameterCount());
}catch (Exception e){
e.printStackTrace();
}
}
}
运行结果