Java Annotation marker annotations

Introduction

A marker annotation is a special kind of annotation with no members.

We use marker annotation to mark an item.

To find out if an annotation is a marker annotation, use the method isAnnotationPresent() defined by the AnnotatedElement interface.

The following code uses a marker annotation.


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

// A marker annotation. 
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker {
}

public class Main {

  // Annotate a method using a marker.
  // Notice that no () is needed.
  @MyMarker//w  w w . j  av  a  2  s . c  o  m
  public static void myMeth() {
    Main ob = new Main();

    try {
      Method m = ob.getClass().getMethod("myMeth");

      // Determine if the annotation is present.
      if (m.isAnnotationPresent(MyMarker.class))
        System.out.println("MyMarker is present.");

    } catch (NoSuchMethodException exc) {
      System.out.println("Method Not Found.");
    }
  }

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



PreviousNext

Related