Java - Target Annotation Type

Introduction

The Target annotation type annotates where to use an annotation type.

It has only one element named value whose value is an array of java.lang.annotation.ElementType enum type.

The following code table lists all constants in the ElementType enum.

Constant Name
Target
ANNOTATION_TYPE
another annotation type declaration. This makes the annotation type a meta-annotation.
CONSTRUCTOR
used to annotate constructors.
FIELD
used to annotate fields and enum constants.
LOCAL_VARIABLE
used to annotate local variables.
METHOD
used to annotate methods.
PACKAGE
used to annotate package declarations.
PARAMETER
used to annotate parameters.
TYPE
used to annotate class, interface (including annotation type), or enum declarations.
TYPE_PARAMETER
used to annotate type parameters in generic classes, interfaces,methods, etc.
TYPE_USE
used to annotate all uses of types.

Example

The following Version annotation type annotates the annotation type declaration with the Target meta-annotation.

Version can only be used on class, interface, enum, and annotation types, a constructors, and methods.

import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface Version {
        int major();
        int minor();
}

The following code is incorrect because Version is used on a field:

class Main{
   // A compile-time error. Version annotation cannot be used on a field.
   @Version(major = 1, minor = 1)
   int id = 110;
}

The following uses of the Version annotation are valid:

@Version(major = 1, minor = 0)
public class Main {
        @Version(major = 1, minor = 0)
        public Main() {
                // Code goes here
        }
        @Version(major = 1, minor = 1)
        public void doSomething() {
                // Code goes here
        }
}

Create Annotation Type That Can Be Used with Any Type Use

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.TYPE_USE})
public @interface Fatal {
}

Annotation Type That Can Be Used with Any Type Use

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ElementType.TYPE_USE})
public @interface NonZero {
}

Demo

import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

@Target({ ElementType.TYPE_USE })
@interface Fatal {
}

@Target({ ElementType.TYPE_USE })
@interface NonZero {
}

class Test {//www .j  a  v  a  2s.  c o m
  public void processData() throws @Fatal Exception {
    double value = 1.0;
    int roundedValue = (@NonZero int) value;
    Test t = new @Fatal Test();
  }

}