How to : Java add custom annotation

by toy

From Java 5, there is a new feature called annotation that provided easier to tag or mark class or method. For example, in JUnit we can ust @Test above a method to let the JUnit engine knows that this class is a test case. Moreover, we can also implement our own annotation as well.

Reference: http://technicalmumbojumbo.wordpress.com/2008/01/13/java-custom-annotations/

Java Reference: http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

I used that reference to implement my own annotation at the first place, but I’m going to memorise that as well in this post.

First, you need to create a new class and make it annotation.

1
2
3
4
5
@Target(ElementType.TYPE)
public @interface IgnoreClass
{

}

The code above will let the java compiler knows that this class is an annotation. You will notice that instead of writing public class IgnoreClass, we write @interface to let the compiler knows. Above that we see @Target and @Retention. First @Target is a tag where we tell the compiler that this annotation can be used in Class, Method Or Field. This is the options we can use.

TYPE: Class, interface, or enum (not annotation)
FIELD: member fields (including enum values)
METHOD: methods (does not include constrcutors)
PARAMETER: method parameter
CONSTRUCTOR: constructor
LOCAL_VARIABLE: local variable or catch clause
ANNOTATION_TYPE: Annotation types
PACKAGE: java package

That’s it, now we have our own annotation to use, we can also have fields in annotation as well.

So this is how we use the annotation

1
2
3
4
@IgnoreClass
public class AClass
{
}

And this is how we check that the class has such annotation

1
2
3
4
5
6
Class[] classes = {AClass.class};
for (Class classObj : classes)
{
     Annotation[] annotations = classObj.getAnnotations();
     // And then we can loop through this array and cast back to the annotation we want.
}

This is a very easy example for creating our own annotation. There are lots of things you can do with annotation. So, you might want to have a look more at the references above.