java中迴圈遍歷實體類的屬性和資料型別以及屬性值
阿新 • • 發佈:2019-01-12
package com.walkerjava.test; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Date; /*** * 遍歷實體類的屬性和資料型別以及屬性值 * * @author LiBaozhen * @date 2013-1-4 上午10:25:02 * @company * @version v1.3 * @see 相關類 * @since 相關/版本 */ public class ReflectTest { public static void reflectTest(Object model) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // 獲取實體類的所有屬性,返回Field陣列 Field[] field = model.getClass().getDeclaredFields(); // 遍歷所有屬性 for (int j = 0; j < field.length; j++) { // 獲取屬性的名字 String name = field[j].getName(); // 將屬性的首字元大寫,方便構造get,set方法 name = name.substring(0, 1).toUpperCase() + name.substring(1); // 獲取屬性的型別 String type = field[j].getGenericType().toString(); // 如果type是類型別,則前面包含"class ",後面跟類名 System.out.println("屬性為:" + name); if (type.equals("class java.lang.String")) { Method m = model.getClass().getMethod("get" + name); // 呼叫getter方法獲取屬性值 String value = (String) m.invoke(model); System.out.println("資料型別為:String"); if (value != null) { System.out.println("屬性值為:" + value); } else { System.out.println("屬性值為:空"); } } if (type.equals("class java.lang.Integer")) { Method m = model.getClass().getMethod("get" + name); Integer value = (Integer) m.invoke(model); System.out.println("資料型別為:Integer"); if (value != null) { System.out.println("屬性值為:" + value); } else { System.out.println("屬性值為:空"); } } if (type.equals("class java.lang.Short")) { Method m = model.getClass().getMethod("get" + name); Short value = (Short) m.invoke(model); System.out.println("資料型別為:Short"); if (value != null) { System.out.println("屬性值為:" + value); } else { System.out.println("屬性值為:空"); } } if (type.equals("class java.lang.Double")) { Method m = model.getClass().getMethod("get" + name); Double value = (Double) m.invoke(model); System.out.println("資料型別為:Double"); if (value != null) { System.out.println("屬性值為:" + value); } else { System.out.println("屬性值為:空"); } } if (type.equals("class java.lang.Boolean")) { Method m = model.getClass().getMethod("get" + name); Boolean value = (Boolean) m.invoke(model); System.out.println("資料型別為:Boolean"); if (value != null) { System.out.println("屬性值為:" + value); } else { System.out.println("屬性值為:空"); } } if (type.equals("class java.util.Date")) { Method m = model.getClass().getMethod("get" + name); Date value = (Date) m.invoke(model); System.out.println("資料型別為:Date"); if (value != null) { System.out.println("屬性值為:" + value); } else { System.out.println("屬性值為:空"); } } } } }
http://blog.csdn.net/dongzhouzhou/article/details/8659836