Search code examples
javaspring-boothibernatehibernate-validatorapache-commons-beanutils

Cannot resolve method 'getProperty' in 'BeanUtils'


I'm trying to make a custom annotation using hibernate validator,found an "old" code right here on stackOverflow but there is a method called

BeanUtils.getProperty ()

which returns me the following error:

Cannot solve method 'getProperty' in 'BeanUtils'

I didn't find anything recent on the internet about it, does this method no longer exist? how can I replace it and maintain functionality?

Here the code I'm referring to:

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;
    }

}

And here's the page where I got this code


Solution

  • So I checked the Spring-Framework BeanUtils.java.

    But there wasn't any method getProperty().

    Then I looked for other BeanUtils.getProperty() methods and there is the Apache Commons BeanUtils.

    Take a look at the class methods/fields and here the getProperty()

    You can also search the PropertyUtils class

    Check here for examples as well.

    Hope it will help. Good luck :)