java类反射获取成员变量


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

//通过反射获取成员变量
public class ReflectDemo4 {
    public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Class<Student> studentClass = Student.class;

        //获取公共成员变量
//        Field[] fields = studentClass.getFields();
//        for (Field field : fields) {
//            System.out.println(field);
//        }

        //获取单个指定的公共成员变量
//        Field address = studentClass.getField("address");
//        System.out.println(address);

        //获取非公共的
//        Field[] declaredFields = studentClass.getDeclaredFields();
//        for (Field declaredField : declaredFields) {
//            System.out.println(declaredField);
//        }

        //获取单个非公共
//        Field name = studentClass.getDeclaredField("address");
//        System.out.println(name);

        //同郭反射给属性赋值
        Constructor<Student> constructor = studentClass.getConstructor();
        Student student = constructor.newInstance();

        Field[] declaredFields = studentClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            declaredField.setAccessible(true);
        }
        declaredFields[0].set(student,"郭奉孝");
        declaredFields[1].set(student,24);
        declaredFields[2].set(student,"魏国");

        System.out.println(student);
    }
}


posted @ 2021-05-03 22:06  code-G  阅读(626)  评论(0编辑  收藏  举报