lundi 23 janvier 2017

Unknown property error while using BeanUtils.getProperty()

Here's my class.

@DateRange.List({
        @DateRange(start = "startDate", end = "endDate", message = "Start date should be earlier than end date.")
})
public class MyClass {
    @NotNull
    @Pattern(regexp = DateConstants.DATE_FORMAT_REGEX, message = "Invalid date format.")
    public String startDate;

    @NotNull
    @Pattern(regexp = DateConstants.DATE_FORMAT_REGEX, message = "Invalid date format.")
    public String endDate;
}

I've added a @DateRange annotation, which is declared as follows.

@Target({TYPE, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = DateRangeValidator.class)
@Documented
public @interface DateRange {
    String message() default "{constraints.daterange}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String start();

    String end();

    @Target({TYPE, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        DateRange[] value();
    }
}

And the validator class is

public class DateRangeValidator implements ConstraintValidator<DateRange, Object> {
    private String startDateFieldName;
    private String endDateFieldName;

    @Override
    public void initialize(final DateRange constraintAnnotation) {
        startDateFieldName = constraintAnnotation.start();
        endDateFieldName = constraintAnnotation.end();
    }

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

        final String startDate = (String) BeanUtils.getProperty(value, startDateFieldName);
        final String endDate = (String) BeanUtils.getProperty(value, endDateFieldName);

        return isValidDateRange(startDate, endDate);
    }

    private boolean isValidDateRange(String start, String end) {
        DateFormat dateFormat = new SimpleDateFormat(DateConstants.DATE_FORMAT);
        try {
            Date startDate = dateFormat.parse(start);
            Date endDate = dateFormat.parse(end);

            if (startDate.before(endDate)) return true;
        } catch (ParseException e) {}

        return false;
    }
}

The validator checks if the start date is before the end date.

While doing so, the BeanUtils.getProperty() is throwing NoClassDefFoundException along with Unknown property 'startDate'.

But the startDate is there in MyClass. The variable is public and named camel case. Why the problem is occurring? Any idea?





Aucun commentaire:

Enregistrer un commentaire