Created
November 21, 2012 09:54
-
-
Save doubledouble/4124051 to your computer and use it in GitHub Desktop.
获取对象属性值,支持嵌套属性
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 获取对象属性值,支持嵌套属性(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