反射机制
-
先通过类名或类(例子:Student)的包名等得到类的Class实例
Student stu = new Student();
Class clazz = 三种方式:如下
Class.forName(类包名) ; stu.getclass方法 ;stu.getName()
-
再通过Constructor类获取类的构造方法
Constructor con = class实例.getConstructor(参数);
-
再通过构造函数创建对象
Student stu = (Student)con.newInstance(参数);
-
得到Student类的所有方法实例
Method[] methods = calzz.getMethods();
-
迭代方法的数组,调用其中的setName和setAge方法,为stu对象的属性赋值
for(Method m:methods){
if(m.getName().startsWith(“setName”)){
m.invoke(stu,“zhangsan”);
}
if(m.getName().startWith(“setAge”))
m.invoke(stu,24);
}
-
用Field类来获取属性,前提类的属性是public
clazz.getName()得到属性名
clazz.getXXX() 来得到一些属性,然后属性能使用一些方法如set()方法
//先得到类的class实例 如:
Class clazz = Class.forName("Student的包名");
//通过class实例获取student类的无参构造方法实例
Constructor con = clazz.getConstructor(null);
//再通过构造函数创建student对象
Student stu = (Student) con.newInstance(null);
//通过class实例获取student类的所有方法实例
Method[] methods = clazz.getMethods();
//迭代methods
for(Method m:methods){
//判断
if(m.getName().startWith("setName")){
//invoke()是调用方法
m.invoke(stu,"zhangsan");
}
}