Marker Annotations In Java

by | Apr 16, 2021 | Java

Home » Java » Marker Annotations In Java

Marker Annotations In Java

Marker annotations are solely used for the purpose of declaration. They are used to mark declarations in Java. Annotations in Java have a higher priority than comments but a lower priority as compared to source code. Unlike comments, annotations have the power to determine the execution of the compiler for a certain code.

What is a Marker Annotation?

Marker annotations are special annotations in Java that do not contain any members or data. As marker interfaces do not contain any members, just declaring the annotation in your code is sufficient for it to influence the output in whatever terms you want. If you want to check whether a marker annotation is present or not, you can do so by invoking the isAnnoationPresent() method. This method is part of the annotated element interface.

A Simple Java Marker Annotation Example

The sample code in this section makes use of a Java annotation marker. As mentioned before, the marker annotation does not contain any member or data. Therefore, it is sufficient to determine whether it is present or absent.

//Code to demonstrate the use of Marker Annotation
import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention (RetentionPolicy.RUNTIME)
@interface MyMarker { }
class Marker
{
@MyMarker
public static void myMethod()
{
Marker obj = new Marker ();
try
{
Method m = obj.getClass().getMethod (“myMethod”);
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 [])
{
myMethod ();
}
}

OUTPUT

MyMarker is Present

//The output from the program confirms the usage of a Marker Annotation as it prints out an affirmative statement.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author