Thursday, June 5, 2014
Today in this article I will show you how to create your own annotation. Here we will start with a very basic annotation and then slowly show you how to include arrays and also how to use default values. We will also show you how to yo use annotations. We have divided our tutorial on creating and using annotations in two parts. The first part meaning this one is a very basic and good one for beginners to start with.
In our first annotation we will just start with an empty annotation specifying only @target and @Retention.
import java.lang.annotation.*;

@Target(value={ElementType.FIELD})
@Retention(value=RetentionPolicy.RUNTIME)
public @interface Author {
}
In the next example you will see that when there is only one value for an annotation then we can omit the name as well as braces{} indicating arrays. The above sample is re-written as
import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
}
In our next example you will see how to mention the target type when it is more than one say FIELD and METHOD.
import java.lang.annotation.*;

@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
}
In our next example we will deal with annotation which has annotation type elements. It looks almost like methods. We will also show you how to use this annotation in a class.
import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
 String name();
}

class MyClass {
 @Author(name="Nirupam")
 int i = 10;
}
In our next and last example of today, we will show you how to mention default values of annotation type elements. It is done using keyword default . If a default value is mentioned, then you can omit adding your own value. But it does not mean that you cannot add your own value, of course you can do it.
import java.lang.annotation.*;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Author {
 String name() default "Nirupam";
}

class MyClass {
 @Author
 int i = 10;
}
In our next and last part we will deal with creating and using advanced annotation. Till then keep coding and keep reading our articles.

0 comments:

Post a Comment

Total Pageviews

Subscribe via Email

Followers


Popular Posts

About Me

My photo

I am a student of BTech Computer Science Engineering from RCCIIT,Kolkata. I am a crazy lover of Java and wants to settle as a Java developer. I have a seven years Java experience with an application developer experience for 2 years. Recently from March 2012 I am a registered S40 app developer for Nokia and has corrected an app of them. I am currently writing blogs to encourage and grow interest in all those who don't know or learning Java.