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

Java:通过反射访问对象的bean类型方法,java,reflection,javabeans,Java,Reflection,Javabeans,这是在不知道/不关心对象的确切类型的情况下访问对象的bean属性的合适方法吗?(或者已经有一个内置方法可以这样做了吗?)当属性不存在或不可用时,是否有适当的异常可以抛出 static private Object getBeanPropertyValue(Object bean, String propertyName) { // access a no-arg method through reflection // following bean naming conventi

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

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

我建议你看一看,而不是自己写


做你想做的事。也不接受异常:-)

如果您不介意第三方依赖性,那么像Commons BeanUtils这样的包装器就很好了。否则,我建议看一下课堂,提供你需要的东西


IllegalArgumentException可能是一个合理的抛出方法,但实际上,几乎任何东西都比吞下异常要好。

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

当然,如果您试图遵守bean标准,那么使用java.beans比直接使用反射更有意义。至于例外情况,吞咽是做错事的必然迹象(在使用反射的情况下,做错事的可能是使用反射)。在这里,即使是方法中未检查的异常也会被吞没。我认为这里没有安全是不言而喻的。