Reading and Writing Custom Annotation

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with Leave a comment on Reading and Writing Custom Annotation

Article on Reading and Writing Custom Annotation with example

We have already discussed the basics of annotation and Meta Annotation in JAVA.  In this article i will explain how to read and write the custom annotation in JAVA.

To define custom Annotation, keyword interface is used preceded by @. Like interface, it also has the method declaration.
To make topic easy, lets I want to create the annotation CopyRight

package com.G2.Annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(value=RetentionPolicy.RUNTIME)
public @interface CopyRight {
	public String owner();
	public String location();
	public String year();
}

To use this annotation in our class, we should use like:

package com.G2.Annotations;

@CopyRight(location="Mumbai",owner="Jitendra Zaa",year="2011")
public class TestAnnotations {
}

Annotation can also have the default values while declaration.
Example:

package com.G2.Annotations;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(value=RetentionPolicy.RUNTIME)
public @interface CopyRight  {
	public String owner() default "Jitendra Zaa";
	public String location() default "Mumbai";
	public String year() default "2011";
}

Program to read the Annotations:

package com.G2.Annotations;

import java.lang.annotation.Annotation;

@CopyRight(location="Mumbai",owner="Jitendra Zaa",year="2011")
public class TestAnnotations {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws ClassNotFoundException {
		TestAnnotations obj = new TestAnnotations();
		obj.display();
	}

	public void display() throws ClassNotFoundException
	{
		Annotation[] annotations = TestAnnotations.class.getAnnotations();
		System.out.println(annotations.length);
		for(Annotation a : annotations)
		{
			CopyRight r = (CopyRight)a;
			System.out.println("Location Value in Annotation : "+r.location());
			System.out.println("Owner Value in Annotation : "+r.owner());
			System.out.println("Year Value in Annotation : "+r.year());
		}

	}
}

Output:

1
Location Value in Annotation : Mumbai
Owner Value in Annotation : Jitendra Zaa
Year Value in Annotation : 2011

Related posts

Leave a Reply

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