原文鏈接:http://blog.csdn.net/tonytfjing/article/details/39755345
原文的代碼如下
- /**
- * 遍歷實體類的屬性和數據類型以及屬性值
- * @param model
- * @throws NoSuchMethodException
- * @throws IllegalAccessException
- * @throws IllegalArgumentException
- * @throws InvocationTargetException
- */
- 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("屬性值爲:空");
- }
- }
- }
- }