```java
/*
定义一个Student类
属性:name(私有的) age(公开的)
方法:无参构造、有参构造、setter和getter方法, toString方法
定义Test测试类, 测试反射获取成员变量方法, 修改age的属性值, 然后获取修改后的值:
Class类
Field[] getFields
Field[] getDeclaredFields
Field getField(String fieldName)
Field getDeclaredField(String fieldName)
Field类
void set(Object obj, Object value)
Object get(Object obj)
*/
public class Test {
public static void main(String[] args) throws ReflectiveOperationException {
// 获取学生类的字节码对象
Class studentClass = Class.forName("com.itheima.practice_02.Student");
// 通过class对象创建学生对象
Object student = studentClass.newInstance();
// Field[] getFields: 获取所有public属性
Field[] publicFields = studentClass.getFields();
for (Field field : publicFields) {
System.out.println(field);
}
// Field[] getDeclaredFields: 获取所有的全部权限的属性
Field[] allFields = studentClass.getDeclaredFields();
for (Field field : allFields) {
System.out.println(field);
}
// Field getField(String fieldName): 获取指定名称的public属性
Field ageField = studentClass.getField("age");
// void set(Object obj, Object value): 修改指定对象的属性值
ageField.set(student, 30);
System.out.println(student);
//Object get(Object obj): 获取指定对象的属性值
int age = ageField.getInt(student);
System.out.println(age);
// Field getDeclaredField(String fieldName): 获取指定名称的所有权限的属性
Field nameField = studentClass.getDeclaredField("name");
System.out.println(nameField);
nameField.get(student); // 直接获取权限不足的属性会报错:
nameField.set(student, "李四"); // 直接修改权限不足的属性会报错:
// java.lang.IllegalAccessException: Class xxx can not access a member of class yyy with modifiers "private"
}
}
```