package J20250806.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author WanJl
 * @version 1.0
 * @title Demo10
 * @description
 * 案例3：字段操作
 *     创建一个Student类，包含私有字段name和age，以及公共字段id。使用反射完成：
 *     获取所有字段（包括私有）并打印名称和类型
 *     修改私有字段age的值
 *     读取私有字段name的值
 * @create 2025/8/6
 */
public class Demo10 {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Student> studentClass = Student.class;
        Constructor<Student> declaredConstructor = studentClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Student student = declaredConstructor.newInstance();

        Field[] declaredFields = studentClass.getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            System.out.println("第"+(i+1)+"成员变量--"+"变量名称："+field.getName()+"变量类型："+field.getType());
        }
        //age这个成员变量的对象
        Field ageField = declaredFields[2];
        //设置检查取消
        ageField.setAccessible(true);
        //给age这个成员变量赋值(指定当前的这个age属性属于哪个Student对象,变量值)
        ageField.set(student,66);
        System.out.println(ageField.get(student));

        Field nameField = declaredFields[1];
        nameField.setAccessible(true);
        System.out.println(nameField.get(student));
    }
}
