/**
* 获取对象中的字段
* @param obj which object you want to find filed
* @param fieldName the field name you want to find
* @return the field you want to find
* @throws Throwable
* @throws NoSuchFieldException
*/
protected Field getField(Object obj,String fieldName) throws NoSuchFieldException {
Class clzz = obj.getClass();
Field[] fields = clzz.getDeclaredFields();
Field dest = null;
while (!hasField(fields,fieldName) && !clzz.getName().equalsIgnoreCase("java.lang.Object")) {
clzz = clzz.getSuperclass();
fields = clzz.getDeclaredFields();
}
if (hasField(fields,fieldName)) {
dest = clzz.getDeclaredField(fieldName);
} else {
throw new NoSuchFieldException("类中没有此字段");
}
return dest;
}
/**
* 判断对象中是否有要找的字段
* @param fields the fields which you want to find
* @param fieldName the field name you want to find
* @return if the field in field return true else return false
*/
private boolean hasField(Field[] fields, String fieldName) {
for (int i = 0; i < fields.length ;i ++) {
if (fields[i].getName().equals(fieldName)) {
return true;
}
}
return false;
}