Marker Annotations

A marker annotation contains no members. It is used to mark a declaration.

To determine if a marker annotation is present, use the method isAnnotationPresent( ). isAnnotationPresent( ) is a defined by the AnnotatedElement interface.

Here is an example that uses a marker annotation.


import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;


@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker {
}

public class Main {
  @MyMarker
  public static void myMethod() throws Exception{
    Main ob = new Main();
      Method m = ob.getClass().getMethod("myMeth");
      if (m.isAnnotationPresent(MyMarker.class)){
        System.out.println("MyMarker is present.");
      }        
  }
  public static void main(String args[]) throws Exception{
    myMethod();
  }
}
Home 
  Java Book 
    Language Basics  

Annotations:
  1. Annotations (Metadata)
  2. Retention Policy
  3. Annotation Default Values
  4. Marker Annotations
  5. Single-Member Annotations
  6. Built-In Annotations