注释字段的读取值
Reading Value of an annotated field
我有一个用 spring 编写的 restful 网络服务。 HTTP 请求被映射到一个 bean(我称之为请求对象)。我在 bean 的每个字段上都有自定义注释。
我的要求是:
1. 获取所有带注释的字段并检查至少提供了一个值。
我的问题是我不知道如何读取带注释字段的值。
我写了下面的自定义注释
public class DocumentModifiedDateValidator implements ConstraintValidator<ValidDocumentModifiedDate, String> {
private String[] validDocumentModifiedDateValues;
public void initialize(ValidDocumentModifiedDate constraintAnnotation) {
//this.validDocumentModifiedDateValues = constraintAnnotation.value();
}
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
boolean canProceed = false;
for(Field field : DocumentSearchRequest_global.class.getDeclaredFields())
{
if (field.isAnnotationPresent(ValidDocumentModifiedDate.class))
{
String name = field.getName();
System.out.println("1.name : "+ name); //Iam able to get the name of the field
System.out.println("2. "+field.getType().getName());
Class<?> targetType = field.getType();
Object objectValue;
try
{
//Idont know if i can use the below to read value of the field???
//Please suggest a way so that
//so that i can read value of every element
objectValue = targetType.newInstance();
Object value = field.get(new String());
System.out.println(value.toString());
}
catch (InstantiationException | IllegalAccessException e)
{
// TODO Auto-generated catch block
}
}
}
}
根据 Spring Validation ,spring 允许您编写自定义验证器并使用注释来引用您的验证器。
我有一个用 spring 编写的 restful 网络服务。 HTTP 请求被映射到一个 bean(我称之为请求对象)。我在 bean 的每个字段上都有自定义注释。 我的要求是: 1. 获取所有带注释的字段并检查至少提供了一个值。 我的问题是我不知道如何读取带注释字段的值。 我写了下面的自定义注释
public class DocumentModifiedDateValidator implements ConstraintValidator<ValidDocumentModifiedDate, String> {
private String[] validDocumentModifiedDateValues;
public void initialize(ValidDocumentModifiedDate constraintAnnotation) {
//this.validDocumentModifiedDateValues = constraintAnnotation.value();
}
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
boolean canProceed = false;
for(Field field : DocumentSearchRequest_global.class.getDeclaredFields())
{
if (field.isAnnotationPresent(ValidDocumentModifiedDate.class))
{
String name = field.getName();
System.out.println("1.name : "+ name); //Iam able to get the name of the field
System.out.println("2. "+field.getType().getName());
Class<?> targetType = field.getType();
Object objectValue;
try
{
//Idont know if i can use the below to read value of the field???
//Please suggest a way so that
//so that i can read value of every element
objectValue = targetType.newInstance();
Object value = field.get(new String());
System.out.println(value.toString());
}
catch (InstantiationException | IllegalAccessException e)
{
// TODO Auto-generated catch block
}
}
}
}
根据 Spring Validation ,spring 允许您编写自定义验证器并使用注释来引用您的验证器。