How to create custom annotations in Java

Ever since Java started supporting annotations, most of the frameworks embraced annotations and now annotations are the best way to define the extra services a class needs. Annotations are cleaner and easier than XML or properties file based alternatives. Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries. Hence annotations are a way to tell what all services a class needs or how it needs to be treated by the run time framework. To create an annotation first step is to define an interface. It is like any normal interface but with an @ infront. ( @interface). The @interface declarations notifies java compiler, that this is custom annotation.

Annotation Definition

package com.stackrules.test;
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) 
public @interface Hello {
	
	boolean active() default true;
 
}

@Target(ElementType.METHOD)  – this annotation is only meant to be applied for methods.

boolean active() – Method declarations must not have any parameters or a throws clause.

Class with @Hello Annotation

public class HelloWorld {
	
	public HelloWorld(){
		
	}
	
	@Hello(active=true)
	public void methodA()	{
		
		System.out.println("Running methodA");
	}
	@Hello(active=false)
	public void methodB(){
		System.out.println("Running methodB");
		
	}
 
}

 Processing the Annotation

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
 
public class AnnotationProcessor {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HelloWorld helloWorld = new HelloWorld();
		for (Method m : HelloWorld.class.getMethods()) {
			// System.out.println(" "+m.getName());
			if (m.isAnnotationPresent(Hello.class)) {
				Annotation annotation = m.getAnnotation(Hello.class);
				try {
					Hello h = (Hello) annotation;
					if (h.active()) {
						m.invoke(helloWorld);
					}
				} catch (Throwable t) {
					t.printStackTrace();
				}
			}
		}
 
	}
 
}

Output

Running methodA

Recap

Created the custom annotation named Hello , applied the annotation to HelloWorld class, Written an AnnotationProcessor ( mimicking framework classes) that processes the annotation.

Leave a Comment