如何获取对象字段上方的@Size注释的值



我需要从@Size注释中拉取属性值

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

这是对 DTO 类型对象字段的@Size约束

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

但是当我尝试获取注释时,我得到

Size annotation = null;

此注释位于dto类型的对象之上,不会进行处理,但是当处理实体时,此注释可见?!!!

使用弹簧引导

错误消息在文件中 -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;
}
}

以下是方法中传递的内容 -getMaxLimitSize((,类型字段

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

请解释为什么 dto 对象对验证器不可见,或者为什么反射看不到验证注释,可以做什么?

如何解决这个问题?

您可以通过调用方法来获取field valueField#get(currentObject)

if (field.isAccessible()) {
Object someValue = field.get(object);
}

最新更新