Java反射练习(二)

这次在运行时使用反射分析对象

获取数据域的实际内容

package com.slliver.reflection;

import java.lang.reflect.Field;

/** * Created with IntelliJ IDEA. * User: Administrator * Date: 2017/4/13 0013 * Time: 下午 21:23 * To change this template use File | Settings | File Templates. */ public class StudentTest {

public static void main(String\[\] args) {
    Student student = new Student("stu20170413212400", "class001", "card001");
    printFieldValue(student);
}

private static void printFieldValue(Student student){
    Class classzz = student.getClass();
    Field\[\] fields = classzz.getDeclaredFields();
    try {
        for(Field field : fields){
            // 类中属性
            String fieldName = field.getName();
            Field property = classzz.getDeclaredField(fieldName);
            // 如果属性的修饰符不是public,设置可访问权限
            if(!property.isAccessible()){
                // 设置访问访问权限
                property.setAccessible(true);
            }

            Object fieldValue = property.get(student);
            System.out.println("\[fileName == >" + fieldName + "\],\[" + "fieldValue == >" + fieldValue + "\]");
        }

    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

}

评论

暂无评论