Java:通过反射访问Object的bean类型方法

时间:2009-10-01 19:21:16

标签: java reflection javabeans

这是否是在不知道/关心其确切类型的情况下访问Object的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?
}

3 个答案:

答案 0 :(得分:3)

如果你不介意第三方依赖,那么像Commons BeanUtils这样的包装器会很好。否则,我建议您查看Java BeanInfo课程以提供您需要的内容。

IllegalArgumentException可能是一个合理的东西,但实际上,几乎任何事情都会比吞下异常更好。

答案 1 :(得分:3)

如果您不能使用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);
    }
}

答案 2 :(得分:2)

嗯......这不会处理布尔值(例如'isActive()`)或嵌套/索引属性。

我建议你看看Commons BeanUtils而不是自己写这个。

BeanUtils.getProperty()做你想要的。不吞下例外: - )

相关问题