0
public class User {

    @NotBlank
    @Size(min=2)
    private final String firstName;

    @NotBlank
    @Size(min=2)
    private final String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

I want to validate properties firstName and lastName. But I don't want to repeat the annotations everytime.

How can I create a custom annotation, so the code will be like

public class User {

    @UserName
    private final String firstName;

    @UserName
    private final String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }
}

and validation will be the same

Romper
  • 2,009
  • 3
  • 24
  • 43
  • 1
    Sure, no problem. Try searching for *JSR 303 custom bean validation* for some examples. – Nico Van Belle Jul 26 '17 at 11:44
  • 1
    Search the [bean validation specification](http://download.oracle.com/otndocs/jcp/bean_validation-1_1-fr-eval-spec/) for “Constraint composition”. – VGR Jul 26 '17 at 12:02

2 Answers2

0

Firstly let me start by saying that annotations are meant to give additional information to the compiler or runtime. For example, when you use annotation @override then it is meant to tell the compiler that this method should override the method of super class.

Now, in your case you are looking for annotation which is meant for runtime, because you want to validate that field is not null etc.

Surely you can create an annotation which would check both the checks you are looking for but you need to also implement the mechanism to ensure that those are being validated (annotation interface which you will create should have retention policy of runtime - @Retention(RetentionPolicy.RUNTIME)). When you use @NotNull then JRE ensure that this field is not NULL but when you want to create a custom annotation @UserName and check that field is not NULL and minimum size is 2 then at runtime you have to ensure that this checks are handled.

Read this about how you can read value of annotation in Java.

As @Nico suggested in his comment, you can search JSR if there is such an annotation which you are looking for, if not, then I think you are better using separate annotations.

hagrawal7777
  • 14,103
  • 5
  • 40
  • 70
0

Chapter 6. Creating custom constraints. Constraint composition

Romper
  • 2,009
  • 3
  • 24
  • 43