Skip to content

Instantly share code, notes, and snippets.

@doubledouble
Created November 21, 2012 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doubledouble/4124051 to your computer and use it in GitHub Desktop.
Save doubledouble/4124051 to your computer and use it in GitHub Desktop.
获取对象属性值,支持嵌套属性
/**
* 获取对象属性值,支持嵌套属性(like el表达式)
* @param obj
* @param property p1.p2
* @return
*/
public static Object getProperty(Object obj, String property) {
if (obj == null || StringUtil.isBlank(property))
return null;
String[] propertyArray = property.split("\\.");
Object value = null;
int methodCount = 0;
Class<?> actualEditable = obj.getClass();
PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(actualEditable);
for (PropertyDescriptor targetPd : targetPds) {
Method readMethod = targetPd.getReadMethod();
if (readMethod != null && targetPd.getName().equals(propertyArray[0])) {
try {
value = readMethod.invoke(obj);
methodCount ++;
if (propertyArray.length > 1) {
value = getProperty(value, propertyArray[1]);
}
break;
}
catch (Throwable ex) {
throw new FatalBeanException("Could not read properties from obj", ex);
}
}
}
if (methodCount == 0) {
throw new NotReadablePropertyException(actualEditable, propertyArray[0]);
}
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment