package J20250806.reflection;

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

/**
 * @author WanJl
 * @version 1.0
 * @title Demo03_FieldTest
 * @description
 * @create 2025/8/6
 */
public class Demo03_FieldTest {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<Person> personClass = Person.class;
        Constructor<Person> personConstructor =
                personClass.getDeclaredConstructor(Integer.class, String.class, Integer.class, String.class);
        //构造方法对象的取消检查
        personConstructor.setAccessible(true);
        //通过反射-构造方法对象创建的Person对象
        Person person = personConstructor.newInstance(16, "张三", 25, "男");
        System.out.println(person);
        //通过反射获取Person类的私有属性
        Field nameField = personClass.getDeclaredField("name");
        //成员变量对象的取消检查
        nameField.setAccessible(true);
        System.out.println(nameField.getName());
        //通过反射-获取Person类的属性，需要传入一个参数，这个参数其实就是通过反射获取构造方法创建的对象。
        //person参数就是目标对象
        Object name = nameField.get(person);
        System.out.println(name);
        //设置name属性的值---person这个参数其实就是目标对象
        nameField.set(person,"王老五");
        System.out.println("--------------------------");
        System.out.println(name);
        System.out.println(nameField.get(person));
        System.out.println(person);

    }
}
