Student 类
package com.itheima.Myreflect3;
public class Student {
private String name;
private int age;
public String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return age
*/
public int getAge() {
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age) {
this.age = age;
}
/**
* 获取
* @return gender
*/
public String getGender() {
return gender;
}
/**
* 设置
* @param gender
*/
public void setGender(String gender) {
this.gender = gender;
}
public String toString() {
return "Student{name = " + name + ", age = " + age + ", gender = " + gender + "}";
}
}
Reflect
package com.itheima.Myreflect3;
import java.lang.reflect.Field;
public class MyReflectDemo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
Class clazz = Class.forName("com.itheima.Myreflect3.Student");
// 获取所有的成员变量
/*Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
}*/
Field name = clazz.getDeclaredField("name");
System.out.println(name);
//获取权限修饰符
int modifiers = name.getModifiers();
System.out.println(modifiers);
// 获取成员变量名
String name1 = name.getName();
System.out.println(name1);
// 获取数据类型
Class<?> type = name.getType();
System.out.println(type);
// 获取成员变量记录的值
Student stu = new Student("zhangsan", 23, "男");
name.setAccessible(true);
String o = (String) name.get(stu);
System.out.println(o);
// 修改对象里面记录的值
name.set(stu, "lisi");
System.out.println(stu);
}
}
笔记
大致思路就是 先获取到成员变量的对象 (先获取类的对象,在得到类中成员变量的对象)
Class clazz = Class.forName("com.itheima.Myreflect3.Student");
Field name = clazz.getDeclaredField("name");
然后用一系列方法对对象进行操作