views:

313

answers:

3

Is this the appropriate way to access bean properties of an Object without knowing/caring about its exact type? (Or is there a built-in method that does this already?) Is there an appropriate exception to throw when a property does not exist or is not available?

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?
}
+1  A: 

Umm... this wouldn't handle booleans (e.g. 'isActive()`) or nested / indexed properties.

I suggest you take a look at Commons BeanUtils instead of trying to write this yourself.

BeanUtils.getProperty() does what you want. Doesn't swallow exceptions either :-)

ChssPly76
+3  A: 

A wrapper such as Commons BeanUtils would be nice if you don't mind the third party dependency. Otherwise, I'd suggest looking at the Java BeanInfo class to provide what you need.

IllegalArgumentException might be a reasonable thing to throw, but really, almost anything would be better than just swallowing the exception.

jsight
Certainly using java.beans makes more sense than using reflection directly if you are trying to obey the beans standard. As for exceptions, swallowing is a sure sign of doing something wrong (in the case of using reflection the thing being done wrong is probably using reflection). Here, even unchecked exceptions from teh method are swallowed. I think it goes without saying that there is no security here.
Tom Hawtin - tackline
+2  A: 

If you can't use Commons BeanUtils, you can get there with jre classes

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);
    }
}