我想用 Java Annotation 验证我的论点。我不知道如何使用为列表编写自己的注释。
这里有一个简单的例子:
class test{
@myAnnotation
List<myObject> myElements =new List<>(); // validated List
}
class myObject{
String name;
}
我的注释界面:
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=myAnnotation_Validator.class)
@Documented
public @interface myAnnotation {
String message() default "List is not valid";
Class <?>[] groups() default {};
Class <?extends Payload>[] payload() default{};
String[] namen();
}
public class myAnnotation_Validator implements ConstraintValidator<myAnnotation, Collection> {
@Override
public void initialize(Kredite_List_Check a) {
// What to do here???
}
@Override
public boolean isValid(Collection t, ConstraintValidatorContext cvc) {
// What to do here???
// How could i get the names from my List "myElements" ?
return false;
}
}
在此示例中,如果我的列表中的每个元素都有另一个名称,则我的列表是有效的。我不知道如何在我的 Validator 类中获取 listobject 以及 myObject 元素的名称。
更新:
我尝试用另一种方式描述我的问题:
如果列表中“myObject”类型的两个元素(“myElements”)同名,则我的列表无效!
我如何通过注释实现这一点?
最佳答案
public class myAnnotation_Validator implements ConstraintValidator<myAnnotation, Collection> {
private String[] names;
@Override
public void initialize(myAnnotation a) {
//get values which are defined in the annotation
names = myAnnotation.namen();
}
@Override
public boolean isValid(Collection objectToValidate, ConstraintValidatorContext cvc) {
if(objectToValidate == null) return true; // use the @NotNull annotation for null checks
for(Object o : objectToValidate) {
//check if value is valid
}
return false;
}
}
在初始化方法中,您可以获得注释中定义的值。 isValid 方法用于验证对象(objectToValidate -> 您的列表对象)。
有关如何编写自定义 validator 的更多信息,请参阅 http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-customconstraints.html#validator-customconstraints-validator
Hibernate-Validator 实现也是一个很好的引用。 https://github.com/hibernate/hibernate-validator/tree/master/engine/src/main/java/org/hibernate/validator/internal/constraintvalidators
希望这个回答对你有帮助。
关于java - 带有 Java 注解的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13162118/