首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >替代BeanUtils.getProperty()

替代BeanUtils.getProperty()
EN

Stack Overflow用户
提问于 2013-10-16 19:20:12
回答 2查看 13.3K关注 0票数 8

我正在寻找BeanUtils.getProperty().only的替代方案,原因是我希望有替代方案,以避免最终用户有多一个依赖项。

我正在处理一个自定义约束,这是我拥有的一段代码

代码语言:javascript
复制
final Object firstObj = BeanUtils.getProperty(value, this.firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, this.secondFieldName);

因为我需要从对象中获取这两个属性。有没有替代方案,没有任何第三方系统,或者我需要从BeanUtilsBean复制这段代码

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-16 19:38:19

BeanUtils非常强大,因为它支持嵌套属性。例如“bean.pro1.pro2”,将Map处理为bean和DynaBeans。

例如:

代码语言:javascript
复制
 HashMap<String, Object> hashMap = new HashMap<String, Object>();
 JTextArea value = new JTextArea();
 value.setText("jArea text");
 hashMap.put("jarea", value);

 String property = BeanUtils.getProperty(hashMap, "jarea.text");
 System.out.println(property);

因此,在您的例子中,我将只编写一个使用java.beans.Introspector的私有方法。

代码语言:javascript
复制
private Object getPropertyValue(Object bean, String property)
        throws IntrospectionException, IllegalArgumentException,
        IllegalAccessException, InvocationTargetException {
    Class<?> beanClass = bean.getClass();
    PropertyDescriptor propertyDescriptor = getPropertyDescriptor(
            beanClass, property);
    if (propertyDescriptor == null) {
        throw new IllegalArgumentException("No such property " + property
                + " for " + beanClass + " exists");
    }

    Method readMethod = propertyDescriptor.getReadMethod();
    if (readMethod == null) {
        throw new IllegalStateException("No getter available for property "
                + property + " on " + beanClass);
    }
    return readMethod.invoke(bean);
}

private PropertyDescriptor getPropertyDescriptor(Class<?> beanClass,
        String propertyname) throws IntrospectionException {
    BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
    PropertyDescriptor[] propertyDescriptors = beanInfo
            .getPropertyDescriptors();
    PropertyDescriptor propertyDescriptor = null;
    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor currentPropertyDescriptor = propertyDescriptors[i];
        if (currentPropertyDescriptor.getName().equals(propertyname)) {
            propertyDescriptor = currentPropertyDescriptor;
        }

    }
    return propertyDescriptor;
}
票数 4
EN

Stack Overflow用户

发布于 2015-03-18 22:37:21

如果你使用SpringFramework,"BeanWrapperImpl“就是你要找的答案:

代码语言:javascript
复制
BeanWrapperImpl wrapper = new BeanWrapperImpl(sourceObject);

Object attributeValue = wrapper.getPropertyValue("attribute");
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19402044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档