How to create custom annotation in Java with example

How to create custom annotation in Java

In this post we will discuss about Java annotations and how to create custom annotation in Java with an example program.

Annotations were introduced in Java 1.5. Annotations are used to provide Meta data for your Java code. Annotations do not directly affect execution of program, but they do affect the way programs are treated by tools and libraries, which can in turn affect the program execution. Java annotations provide additional Meta information about your API and are typically used for the following purposes:

  • Compiler instructions
  • Build-time instructions
  • Run-time instructions (you might be knowing that, when running a test class, the JUnit framework scans the class for methods that are annotated with @Test and runs only those methods).

Java has 3 built-in annotations that you can use to give instructions to the Java compiler. These annotations are:

  • @Deprecated – used to mark a class, method or field as deprecated, meaning it should no longer be used.
  • @Override – used above methods to indicate that the method override a method in a super class. If the method does not match a method in the super class, the compiler will give you an error.
  • @SuppressWarnings – makes the compiler suppress warnings for a given method / field.

 

Java annotations can be used at build-time, when you build your project. Build tools may scan your Java code for specific annotations and generate source code or other files based on these annotations. Normally, Java annotations will not be present in the source code after compilation. But it is possible to define your own annotations that are available at run-time. These annotations can then be accessed via Java Reflection, and used to give instructions to your program, or some third party API.

Many popular Java frameworks like Spring, Hibernate, JUnit etc heavily rely on annotations. In Jersey web service, annotations are used to determine request flow. For example, the @PATH annotation binds a request URI to a method.

Creating Your Own Annotations

Typical application programmers will never have to define an annotation type, but it is possible to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Annotation type declarations are similar to normal interface declarations. An at-sign (@) precedes the interface keyword. Here is an example annotation type declaration:

This example defines an annotation called CustomAnnotation which has four elements. The @interface keyword signals to the Java compiler that this is a Java annotation definition.

Each element is defined similar to a method definition in an interface. Each method declaration defines an element of the annotation type. Method declarations must not have any parameters or a throws clause. Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types.

Once an annotation type is defined, you can use it to annotate declarations. An annotation is a special kind of modifier, and can be used anywhere that other modifiers (such as public, static, or final) can be used. By convention, annotations precede other modifiers. Annotations consist of an at-sign (@) followed by an annotation type and a parenthesized list of element-value pairs. The values must be compile-time constants. Here is a method declaration with an annotation corresponding to the annotation type declared above

You can also specify default values for an element so that the element becomes optional and can be left out in method declaration.

Now the method declaration can be,

 

Marker Annotation

An annotation type with no elements is termed a marker annotation type. For example,

public @interface MarkerAnnotation {},

and a corresponding method declaration would be,

@MarkerAnnotation

public static void testMethod() { …}

Meta Annotations

Java Meta Annotations annotate another annotation. These are discussed below.

@Retention

@Retention can be used to annotate another annotation. A custom annotation can be made available at runtime by annotating it with the @Retention annotation. The @Retention annotation signals to the Java compiler and JVM that the custom annotation should be available via reflection at runtime.

Now, the annotation can be inspected at run time via Java reflection.

The RetentionPolicy class contains two more values,

  • CLASS – the annotation will be stored in the .class file, but not available at runtime. This is the default retention policy.
  • SOURCE – the annotation is only available in the source code, and not in the .class files and not at runtime. If you create your own annotations for use with build tools that scan the code, you can use this retention policy. That way the .class files are not polluted unnecessarily.

 

@Target

The @Target annotation allows you to specify where this annotation can be used, e.g., the class, fields, methods, etc.

This example shows that the annotation can only be used to annotate methods. The list of target types can be found here,

https://docs.oracle.com/javase/7/docs/api/java/lang/annotation/ElementType.html


@Documented

The @Documented annotation is used to signal to the JavaDoc tool that your custom annotation should be included in the JavaDoc for classes using your custom annotation. Here is an example:

 

@Inherited

Indicates that an annotation type is automatically inherited. The @Inherited annotation signals that a custom Java annotation used in a class will be inherited by subclasses inheriting from that class. Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class.

 

 

In this example, the MySubClass automatically inherits the annotation @CustomAnnotation. This means that when sub class is queried for annotations through Java reflection, the inherited annotations in the super class will also be returned.

Here is a Java program using custom annotation to simulate a simple unit testing framework.

 

Hope you find the tutorial useful. If you have any comments, post it in the comments section.

 

The following two tabs change content below.
Working as a Java developer since 2010. Passionate about programming in Java. I am a part time blogger.

Add Comment

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