Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lists with Java Annotations

I want to validate my arguments with Java Annotation. I don't know how to use write a own Annotation for Lists.

Here an simple example:

class test{

    @myAnnotation
    List<myObject> myElements =new List<>(); // validated List
}

class myObject{

        String name;
 }

my Annotation Interface:

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

}

In this Example my List is valid, if each element from my List has another name. I don't know how I get the listobject in my Validator class and the names of myObject-elements.

UPDATE:

I try to describe my question in another way:

my list is not valid if two elements from type "myObject" in my list ("myElements") have the same name!

How could I realize this with Annotations?

like image 719
JavaNullPointer Avatar asked Oct 31 '12 16:10

JavaNullPointer


1 Answers

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

In the initialize method you can get the values, which are defined in the annotation. The isValid method is used to validate the object (objectToValidate -> your list object).

For more information on how to write a custom validator see http://docs.jboss.org/hibernate/validator/4.3/reference/en-US/html/validator-customconstraints.html#validator-customconstraints-validator

Also the Hibernate-Validator implementation is a good reference. https://github.com/hibernate/hibernate-validator/tree/master/engine/src/main/java/org/hibernate/validator/internal/constraintvalidators

I hope this answer helps you.

like image 176
matthias Avatar answered Oct 04 '22 13:10

matthias