8

我正在寻找替代。BeanUtils.getProperty()我想要替代的唯一原因是避免最终用户有更多的依赖。

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

final Object firstObj = BeanUtils.getProperty(value, this.firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, this.secondFieldName);

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

4

2 回答 2

15

如果您使用 SpringFramework,“BeanWrapperImpl”就是您要寻找的答案:

BeanWrapperImpl wrapper = new BeanWrapperImpl(sourceObject);

Object attributeValue = wrapper.getPropertyValue("attribute");
于 2015-03-18T14:37:21.053 回答
4

BeanUtils 非常强大,因为它支持嵌套属性。EG“bean.prop1.prop2”,Map将 s 当作 bean 和 DynaBeans 处理。

例如:

 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.

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;
}
于 2013-10-16T11:38:19.463 回答