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
