0

I need to pull over the field the attribute value from the @Size annotation

private static int getMaxLimitSize(Field field){

    field.setAccessible(true);
    Size annotation = field.getAnnotation(Size.class);

    int zero = 0;

    if(annotation == null) return zero;

    return annotation.max();

}

here is the @Size constraint over the dto type object field

 @Size(message = "{validate.documentid.size}", max = 36)
private String documentId;

But when I try to get an annotation, I get null

Size annotation = null;

This annotation is above objects of type dto and is not processed, but when the entity is processed, then this annotation is visible ?!!!

using Spring Boot

the error messages are in the file - ValidationMessages.properties

@Configuration
public class ServiceConfig implements WebMvcConfigurer {



    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setDefaultEncoding("UTF-8");
        source.setBasename("classpath:ValidationMessages");
        return source;
    }

    @Nullable
    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
        validator.setValidationMessageSource(messageSource());
        return validator;
    }

}

Here's what is passed in the method - getMaxLimitSize(), type Field

private static void processLimitValidateForField(Field field, Object object, List<Object> values){

    Class<?> type = field.getType();
    String typeName = type.getSimpleName();

    boolean isTypeClassOfString = isStringType(typeName);

    int limitString = 0;

    if(isTypeClassOfString){
        limitString = getMaxLimitSize(field);
        setValue(field, typeName, object, values, limitString);
    } else {
        setValue(field, typeName, object, values, limitString);
    }
}

Please explain why the dto object is not visible to the validator, or why reflection does not see the validate annotation and what can be done?

How can this be fixed ?

skyho
  • 1,438
  • 2
  • 20
  • 47

1 Answers1

0

you can get field value by calling the method Field#get(currentObject)

if (field.isAccessible()) {
    Object someValue = field.get(object);
}
Jonathan JOhx
  • 5,784
  • 2
  • 17
  • 33