Jin Kwon
Jin Kwon

Reputation: 21996

What is ElementType.CONSTRUCTOR for?

I'm learning Annotations and Annotation Processors.

I encountered with javax.validation.constraints.NotNull with its declaration of

@Target(value={METHOD,FIELD,ANNOTATION_TYPE,CONSTRUCTOR,PARAMETER})
@Retention(value=RUNTIME)
@Documented
@Constraint(validatedBy={})
public @interface NotNull

I'm already a little familiar with this annotation.

@NotNull
public Integer getAge() {
    return age;
}

@NotNull
private String name;

private int age;

What kind of usages for this @NotNull with ElementType.CONSTRUCTOR?

Upvotes: 4

Views: 1502

Answers (1)

Buhake Sindi
Buhake Sindi

Reputation: 89169

ElementType.CONSTRUCTOR states that the annotation can be classified on constructor level (when specified @Target on the annotation declaration).

Example:

@Entity
@Table(name = "Request")
public class Request implements Serializable {

    @NotNull
    public Request() {

    }
}

The Beans Validation Specification (1.0 final) states the following (in chapter 2.1 Constraint annotation):

Constraint annotations can target any of the following ElementTypes:

  • FIELD for constrained attributes
  • METHOD for constrained getters
  • TYPE for constrained beans
  • ANNOTATION_TYPE for constraints composing other constraints.

While other ElementTypes are not forbidden, the provider does not have to recognize and process constraints placed on such types. Built-in types do support PARAMETER and CONSTRUCTOR to allow Bean Validation provider specific extensions. It is considered good practice to follow the same approach for custom annotations.

In essence, though there hasn't been a constructive/useful example for using @NotNull on constructor level, the specification declares that it's good practice to include the ElementType on annotations (as the built-in annotations contains them already).

I hope this helps.

Upvotes: 2

Related Questions