public class ClassUtil {
private static final String METHOD_PREFIX = "get"; // 约定俗称的getter()方法前缀
/**
* 根据field名称获取field的值<br/>
* 当field允许直接获取的时候,直接返回<br/>
* 否则通过查找约定俗称的get+Field(field首字母大写)的公共成员方法来获取<br/>
* 最后直接返回null
*
* @param object
* @param fieldName
* @return Object
* @throws UnsupportedOperationException
*/
public static Object getValueByFieldName(Object object, String fieldName) {
if (object == null || fieldName == null || fieldName.isEmpty()) {
return null;
}
Object value = null;
Class objectClass = object.getClass();
try {
Field field = objectClass.getField(fieldName);
if (field != null) {
if (field.isAccessible()) {
try {
value = field.get(object);
return value;
} catch (Exception e) {
// since we have checked the field by Class.getField method,so this won't happened
}
} else {
String methodName = METHOD_PREFIX + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
Method method = objectClass.getMethod(methodName, null);
if (method != null && !method.isAccessible()) {
try {
value = method.invoke(object, null);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
return value;
}
} catch (NoSuchMethodException e) {
// since we can't find this method,so just break and return null
}
}
}
} catch (SecurityException e) {
} catch (NoSuchFieldException e) {
}
return value;
}
}