这次在运行时使用反射分析对象
获取数据域的实际内容
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 {
1public static void main(String\[\] args) { 2 Student student = new Student("stu20170413212400", "class001", "card001"); 3 printFieldValue(student); 4} 5 6private static void printFieldValue(Student student){ 7 Class classzz = student.getClass(); 8 Field\[\] fields = classzz.getDeclaredFields(); 9 try { 10 for(Field field : fields){ 11 // 类中属性 12 String fieldName = field.getName(); 13 Field property = classzz.getDeclaredField(fieldName); 14 // 如果属性的修饰符不是public,设置可访问权限 15 if(!property.isAccessible()){ 16 // 设置访问访问权限 17 property.setAccessible(true); 18 } 19 20 Object fieldValue = property.get(student); 21 System.out.println("\[fileName == >" + fieldName + "\],\[" + "fieldValue == >" + fieldValue + "\]"); 22 } 23 24 } catch (NoSuchFieldException e) { 25 e.printStackTrace(); 26 } catch (IllegalAccessException e) { 27 e.printStackTrace(); 28 } 29}
}