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

Anonymous Attribute Annotations 

Some times the value provided to Annotation becomes obvious from Annotation name itself and we don't need to specify the attribute name explicitly. Such attributes are specified with attribute name value and it must be the only attribute for such Annotation. Two such Annotations are shown below,

File Name  :  
com/bethecoder/tutorials/annotations/noattribute/Author.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.annotations.noattribute;

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

File Name  :  
com/bethecoder/tutorials/annotations/noattribute/VersionHistory.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.annotations.noattribute;

/**
 * Permitted types for annotation attributes
 
 * 1. primitive type
 * 2. String
 * 3. Class
 * 4. annotation 
 * 5. enumeration 
 * 6. 1-dimensional arrays
 */
public @interface VersionHistory {
  String [] value();
}
   

We can see that attribute name value is optional. Its usage is shown below,

File Name  :  
com/bethecoder/tutorials/annotations/noattribute/Source.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.annotations.noattribute;

@Author("Author1")
@VersionHistory("1.0")
public class Source {

  private int fieldOne;
  private String fieldTwo;
  
  @Author("Author2")
  @VersionHistory({ "1.0""2.0" })
  public Source(int fieldOne, String fieldTwo) {
    super();
    this.fieldOne = fieldOne;
    this.fieldTwo = fieldTwo;
  }

  @Author("Author3")
  @VersionHistory({ "1.0""2.0""3.0" })
  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;
  }
  
}
   



 
  


  
bl  br