tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Java > Annotations > Target Annotation

Target Annotation 

The Annotation defined is by default applicable to all java constructs such as class, interface, enumerations, constructors, fields, methods, method parameters, local variables, packages and Annotations. However we can restrict this behavior by specifying target with @Target annotation.

The possible targets are listed below,

  • ElementType.TYPE
    Applicable to Java classes, interfaces, enumerations and Annotations.
  • ElementType.FIELD
    Applicable to Java fields.
  • ElementType.METHOD
    Applicable to Java methods.
  • ElementType.PARAMETER
    Applicable to Java method parameters.
  • ElementType.CONSTRUCTOR
    Applicable to Java class constructors.
  • ElementType.LOCAL_VARIABLE
    Applicable to Java local variables.
  • ElementType.ANNOTATION_TYPE
    Applicable to Java annotations.
  • ElementType.PACKAGE
    Applicable to Java packages.

A simple Annotation targeted to java types is shown below,

File Name  :  
com/bethecoder/tutorials/annotations/targets/Author.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.annotations.targets;

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

/**
 * Permitted types for annotation attributes
 
 * 1. primitive type
 * 2. String
 * 3. Class
 * 4. annotation 
 * 5. enumeration 
 * 6. 1-dimensional arrays
 */
@Target(ElementType.TYPE)
public @interface Author {
  String name();
  String creationDate();
}
   

We can use this Annotation only with classes, interfaces, enumerations and Annotations. Its usage is shown below,

File Name  :  
com/bethecoder/tutorials/annotations/targets/Source.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
package com.bethecoder.tutorials.annotations.targets;

@Author(name = "Author1", creationDate="01/01/2500")
public class Source {

  private int fieldOne;
  private String fieldTwo;
  
  public Source(int fieldOne, String fieldTwo) {
    super();
    this.fieldOne = fieldOne;
    this.fieldTwo = fieldTwo;
  }

  public int getFieldOne() {
    return fieldOne;
  }
  
  public void setFieldOne(int fieldOne) {
    this.fieldOne = fieldOne;
  }
  
  public String getFieldTwo() {
    return fieldTwo;
  }
  
  public void setFieldTwo(String fieldTwo) {
    this.fieldTwo = fieldTwo;
  }
  
}
   


                    Print

   



Books Recommendation

 
 
bl  br