java.lang.annotation

Class Level Annotation

TestAnnotation.java

package com.xxx.www;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE}) //on class level
public @interface TestAnnotation
{
   String test();
   String createdBy() default "dsin";
}

Class

@TestAnnotation(
test = "test",
createdBy = "dsin test"
)
public class TestExample {

...

}

USAGE

if (obj.isAnnotationPresent(TestAnnotation.class)) {
   // way1:
   Annotation annotation = obj.getAnnotation(TestAnnotation.class);
   TestAnnotation testerInfo = (TestAnnotation) annotation;

   System.out.printf("%nTest :%s", testerInfo.test());
   System.out.printf("%nCreatedBy :%s", testerInfo.createdBy());
   // way2:
   obj.getAnnotation(TestAnnotation.class).test();
}

If we want to put value to an annotation, ( i.e. @TestAnnotation(“test”) ), just use value() method.

public @interface TestAnnotation
{
   String value();
}

ref : http://www.mkyong.com/java/java-custom-annotations-example/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s