Java Marker annotation

In this chapter you will learn:

  1. How to create and use marker annotation in Java
  2. Example - Java Marker annotation

Description

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.

Example

Here is an example that uses a marker annotation.


import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
//from  ww  w  . ja v a2s. c o m

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

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

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to create and use single member annotation
  2. Example - Java Single-Member Annotations
  3. How to set a default value for a member in an annotation
Home »
  Java Tutorial »
    Java Langauge »
      Java Annotations
Java Annotations
Java Annotation retention policy
Java Annotation reflection
Java Annotation Default Values
Java Marker annotation
Java Single-Member Annotations
Java Built-In Annotations