How to create a Custom Annotation in Java

Points To Remember

  • An annotation can be used as a replacement of interfaces.
  • You can make both empty/marker annotations and annotations with methods.
  • You can define the retention policy for the annotation and where the annotation can be used.

Program : Create A Custom Annotation

The following program creates a custom empty annotation.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Table {

 public String name() default "table";
}

The above class can be used as a custom annotation with only one method name with a default value. This annotation can be applied only to the class i.e it is class level annotation and can not be applied to any member of a class.

The following program creates a custom annotation with methods defined.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
 public String name() default "";
}
In the above example the annotation @Column can be applied only to the fields of a class and not at class level or method level.

@Table(name="user_table")
public class User {

 @Column(name="ekiras")
 private String username;

 public String password;
}
The above code represents how we can use the annotations @Table and @Column to annotate in any pojo class like the class User mentioned above.
public class RunTest {

 public static void main(String args[]){
  test();
  
 }

 public static void test(){
  Table table = User.class.getAnnotation(Table.class);
  if(table!=null){
   System.out.println("Class is annotated with @Table and name="+table.name());
   Field[] fields = User.class.getFields();
   for(Field field : fields){
    Column column = field.getAnnotation(Column.class);
    if(column!=null)
     System.out.println("Field "+field.getName() +" annotated with @Column name="+column.name());
    else {
     System.out.println("Field "+field.getName() +" is not annotated with @Column");
    }
   }
  }
 }
 
}
Class is annotated with @Table and name=user_table
Field username annotated with @Column name=ekiras
Field password is not annotated with @Column



No comments:

Powered by Blogger.