无法解析“BeanUtils”中的方法“getProperty”

时间:2021-03-28 21:54:29

标签: java spring-boot hibernate hibernate-validator apache-commons-beanutils

我正在尝试使用 hibernate 验证器制作自定义注释,在 stackOverflow 上找到了一个“旧”代码,但有一个方法叫做

BeanUtils.getProperty ()

返回以下错误:

Cannot solve method 'getProperty' in 'BeanUtils'

我在互联网上没有找到任何关于它的最新信息,这种方法不再存在了吗?如何更换它并保持功能?

这里是我指的代码:

package br.com.bandtec.projetocaputeam.dominio.validator;

import org.springframework.beans.BeanUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.InvocationTargetException;

/**
 * Implementation of {@link NotNullIfAnotherFieldHasValue} validator.
 **/
/**
 * Implementation of {@link NotNullIfAnotherFieldHasValue} validator.
 **/
public class NotNullIfAnotherFieldHasValueValidator
        implements ConstraintValidator<NotNullIfAnotherFieldHasValue, Object> {

    private String fieldName;
    private String expectedFieldValue;
    private String dependFieldName;

    @Override
    public void initialize(NotNullIfAnotherFieldHasValue annotation) {
        fieldName          = annotation.fieldName();
        expectedFieldValue = annotation.fieldValue();
        dependFieldName    = annotation.dependFieldName();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext ctx) {

        if (value == null) {
            return true;
        }

        try {
            String fieldValue       = BeanUtils.getProperty(value, fieldName);
            String dependFieldValue = BeanUtils.getProperty(value, dependFieldName);

            if (expectedFieldValue.equals(fieldValue) && dependFieldValue == null) {
                ctx.disableDefaultConstraintViolation();
                ctx.buildConstraintViolationWithTemplate(ctx.getDefaultConstraintMessageTemplate())
                        .addNode(dependFieldName)
                        .addConstraintViolation();
                return false;
            }

        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
            throw new RuntimeException(ex);
        }

        return true;
    }

}

还有here's我得到这个代码的页面

1 个答案:

答案 0 :(得分:1)

所以我检查了 Spring-Framework BeanUtils.java

但是没有任何方法getProperty()

然后我寻找了其他 BeanUtils.getProperty() 方法,找到了 Apache Commons BeanUtils

看看类 methods/fields 和这里的 getProperty()

您也可以搜索PropertyUtils

检查 here 以获取示例。

希望它会有所帮助。祝你好运:)