这是访问对象的bean属性而不知道/关心其确切类型的适当方式吗? (或者是否有内置方法已经这样做?)当属性不存在或不可用时,是否存在适当的异常?Java:通过反射访问对象的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?
}
当然使用的java.beans更有意义比使用反射直接,如果你到达那里试图服从豆类标准。对于例外情况,吞咽是做错事的明确标志(在使用反射的情况下,错误的事情可能是使用反射)。在这里,即使是来自teh方法的未经检查的异常也被吞下。我认为不言而喻,这里没有安全保障。 – 2009-10-01 19:52:51