【问题标题】:Cannot resolve method 'getProperty' in 'BeanUtils'无法解析“BeanUtils”中的方法“getProperty”
【发布时间】:2021-03-28 21:54:29
【问题描述】:

我正在尝试使用休眠验证器进行自定义注释,在 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我获得此代码的页面

【问题讨论】:

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


    【解决方案1】:

    所以我检查了Spring-FrameworkBeanUtils.java

    但是没有任何方法getProperty()

    然后我寻找其他 BeanUtils.getProperty() 方法,发现有 Apache Commons BeanUtils

    查看methods/fields 类,这里是getProperty()

    你也可以搜索PropertyUtils

    请查看here 以获取示例。

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

    【讨论】:

    • 谢谢!我整天都在寻找可以帮助我的东西,我什至不认为它们可能是不同的类方法你救了我!
    • 很高兴听到 :) 我们都处于同样的境地。继续前进,祝你好运:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2016-01-15
    • 2015-06-10
    • 2019-08-28
    相关资源
    最近更新 更多