这是访问对象的bean属性而不知道/关心它的确切类型的合适方法吗?(或者是否有内置方法已经执行此操作?)当属性不存在或不可用时,是否存在适当的异常抛出?
static private Object getBeanPropertyValue(Object bean, String propertyName) {
// access a no-arg method through reflection
// following bean naming conventions
try {
Method m = bean.getClass().getMethod(
"get"
+propertyName.substring(0,1).toUpperCase()
+propertyName.substring(1)
, null);
return m.invoke(bean);
}
catch (SecurityException e) {
// (gulp) -- swallow exception and move on
}
catch (NoSuchMethodException e) {
// (gulp) -- swallow exception and move on
}
catch (IllegalArgumentException e) {
// (gulp) -- swallow exception and move on
}
catch (IllegalAccessException e) {
// (gulp) -- swallow exception and move on
}
catch (InvocationTargetException e) {
// (gulp) -- swallow exception and move on
}
return null; // it would be better to throw an exception, wouldn't it?
}
如果您不能使用Commons BeanUtils,则可以使用jre类到达那里
java.beans.Introspector
BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
for(PropertyDescriptor pd : descriptors)
{
if(pd.getName().equals(propertyName)
{
return pd.getReadMethod().invoke(bean, (Object[])null);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句