替代BeanUtils.getProperty()

Ume*_*thi 5 java apache-commons

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

我正在研究自定义约束,这是我的一段代码

final Object firstObj = BeanUtils.getProperty(value, this.firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, this.secondFieldName);
Run Code Online (Sandbox Code Playgroud)

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

nek*_*739 7

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

BeanWrapperImpl wrapper = new BeanWrapperImpl(sourceObject);

Object attributeValue = wrapper.getPropertyValue("attribute");
Run Code Online (Sandbox Code Playgroud)

  • **注意**:从2020年开始,Spring建议不要直接实例化`BeanWrapperImpl`,而是使用`PropertyAccessorFactory.forBeanPropertyAccess(sourceObject)`。 (6认同)

Ren*_*ink 5

BeanUtils 非常强大,因为它支持嵌套属性。EG“bean.prop1.prop2”,将Maps 处理为 beans 和 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);
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,我只会编写一个使用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;
}
Run Code Online (Sandbox Code Playgroud)