Java Annotations
- Annotation(Metadata) Concepts
- The Built-In Annotation in java.lang package Examples
- The Built-In Annotation in java.lang.annotation package Examples
- Some Restriction
Annotation(Metadata) Concepts |
A new facility was added to java 5 that enables you to embed supplemental information into a source file. This information is called an annotation, does not change the actions of program.
However, this information can be used by various tools during both development and deployment.
The term metadata is also used to refer to this feature, but the term annotation is the most descriptive and more commonly used.
The Built-In Annotation
Java defines many built-in annotations. Most are specialized , but seven are general purpose.
Four are imported from java.lang.annotation
- @Retention : It is designed to be used only as an annotation to another annotation.
- @Documented : It is marker interface that tells a tool that an annotation is to be documented.
- @Inherited : It is a marker annotation that can be used only on another annotation declaration.
- @Target : It specifies the types of declaration to which an annotation can be applied.It is designed to be used only as an annotation to another annotation.
@Target takes one of the argument, which must be a constant from the ElementType enumeration.
Target Constant | Annotation can be applied to |
---|---|
ANNOTATION_TYPE | another annotation |
CONSTRUCTOR | constructor |
FIELD | field |
LOCAL_VARIABLE | local Variable |
METHOD | method |
PACKAGE | package |
PARAMETER | parameter |
TYPE | Class, interface, enumeration |
As for example to specify that an annotation applies only on fields and local variables.
@Target ( { ElementType.FIELD, ElementType.LOCAL_VARIABLE} )
Three are included in java.lang
- @Override : It is a marker annotation that can be used only on methods. A method annotated with @override must override a method from a superclass. if it is not , a compile time error will be result.
- @Deprecated : It is a marker annotation. It indicates that a declaration is obsolete and has been replaced by a newer form.
- @SuppressWarnings : It specifies that one or more warnings that might be issued by the compiler to be suppressed. The warnings to suppress are specified by name, in String form.
The Built-In Annotation in java.lang package Examples |
@Override Example
OvTest.java
// will generate compilation error because disp method is not present in Test class.
// if u define disp method in Test, error will go.
class Test
{
}
class OvTest extends Test
{
@Override
void disp()
{
}
}
Output
c:\>javac OvTest.java
OvTest.java:12: error: method does not override or implement a method from a sup
ertype
@Override
^
1 error
c:\>
@Deprecated Example
deprecatedTest.java
class Test
{
@Deprecated //deprecation warnings will appear during compilation if you use disp method as used below
void disp()
{
System.out.println("Hello World!");
}
}
class deprecatedTest
{
public static void main(String[] args)
{
Test t=new Test();
t.disp();
}
}
Output
c:\>javac deprecatedTest.java
Note: deprecatedTest.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
c:\>java deprecatedTest
Hello World!
c:\>
@SuppressWarnings Example
deprecatedTest.java
class Test
{
@Deprecated
void disp()
{
System.out.println("Hello World!");
}
}
class deprecatedTest
{
@SuppressWarnings({"deprecation"})
//deprecation warnings will not appear during compilation
public static void main(String[] args)
{
Test t=new Test();
t.disp();
}
}
Output
c:\>javac deprecatedTest.java
c:\>java deprecatedTest
Hello World!
c:\>
The Built-In Annotation in java.lang.annotation package Examples |
@Retention Example
Before exploring annotation, it is necessary to discuss annotation retention policy.
A retention policy determines at what point an annotation is discarded.
Java defines three such policies which are encapsulated within the java.lang.annotation.RetentionPolicy enumeration.
- SOURCE : an annotation with a retention policy of SOURCE is only in the source file and is discarded during compilation.
- CLASS : An annotation with a retention policy of CLASS is stored in the .class file during compilation and is not available through the JVM during the runtime.
- RUNTIME : An annotation with a retention policy of RUNTIME is stored in the .class file during compilation and is available through the JVM during the runtime.it offers the greatest annotation persistence.
Syntax:
@Retention(retention-policy)
MyAnno.java
// An annotation type declaration.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
Marker Annotation
It is special kind of annotation that contains no members. It is sole purpose to mark a declaration. Thus, its presence as an annotation is sufficient.
import java.lang.annotation.*;
import java.lang.reflect.*;
// A marker annotation.
@Retention(RetentionPolicy.RUNTIME)
@interface MyMarker { }
class Marker {
// Annotate a method using a marker.
// Notice that no ( ) is needed.
@MyMarker
public static void myMeth() {
Marker ob = new Marker();
try {
Method m = ob.getClass().getMethod("myMeth");
// Determine if the annotation is present.
if(m.isAnnotationPresent(MyMarker.class))
System.out.println("MyMarker is present.");
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}
Single value Annotation
A Single-member annotation contains only one member. It works like a normal annotation except that it allows a shorthand form of specifying the value of the member.
import java.lang.annotation.*;
import java.lang.reflect.*;
// A single-member annotation.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.CONSTRUCTOR,ElementType.METHOD})
@interface MySingle {
String value(); // this variable name must be value
}
class Single {
// Annotate a method using a marker.
@MySingle("James1")
Single()
{
}
@MySingle("James")
public static void myMeth() {
Single ob = new Single();
try {
Method m = ob.getClass().getMethod("myMeth");
MySingle anno = m.getAnnotation(MySingle.class);
System.out.println(anno.value()); // displays 100
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}
Using Default values
You can give annotation members default values that will be used if no value is specified when the annotation is applied.
Syntax:
type member() default value;
import java.lang.annotation.*;
import java.lang.reflect.*;
// An annotation type declaration that includes defaults.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str() default "Testing";
int val() default 9000;
}
class Meta3 {
// Annotate a method using the default values.
@MyAnno()
public static void myMeth() {
Meta3 ob = new Meta3();
// Obtain the annotation for this method
// and display the values of the members.
try {
Class c = ob.getClass();
Method m = c.getMethod("myMeth");
MyAnno anno = m.getAnnotation(MyAnno.class);
System.out.println(anno.str() + " " + anno.val());
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}
@Documented Example
It is marker interface that tells a tool that an annotation is to be documented.
Person.java
import java.lang.annotation.*;
/**
* this is person class helping to extends in any other
*/
@Documented
public class Person
{
public String pname;
public int age;
/**
* this is show method
*/
public void show()
{
}
/**
* this is disp method
*/
@Deprecated
public void disp()//absolete
{
System.out.println("Hi I AM james bond");
}
public void disp1()
{
System.out.println("Hi I AM james bond");
}
}
Output
c:\D DRV\doc123>javadoc Person.java
Loading source file Person.java...
Constructing Javadoc information...
Standard Doclet version 1.7.0_03
Building tree for all the packages and classes...
Generating \Person.html...
Generating \package-frame.html...
Generating \package-summary.html...
Generating \package-tree.html...
Generating \constant-values.html...
Building index for all the packages and classes...
Generating \overview-tree.html...
Generating \index-all.html...
Generating \deprecated-list.html...
Building index for all classes...
Generating \allclasses-frame.html...
Generating \allclasses-noframe.html...
Generating \index.html...
Generating \help-doc.html...
c:\>
After executing javadoc command you will find index.html file is gertting created during documentation. Now try to execute as below in browser, and you will find that annotation and comments have documented
@Inherited Example
- This is a bit of a complex annotation type. It indicates that the annotated class with this type is automatically inherited.
- More specifically, if you define an annotation with the @Inherited tag, then annotate a class with your annotation, and finally extend the class in a subclass, all properties of the parent class will be inherited into its subclass.
myChildObject.java
//First, define your annotation:
@Inherited
public @interface myParentObject {
boolean isInherited() default true;
String doSomething() default "Do what?";
}
//Next, annotate a class with your annotation:
@myParentObject
public Class myChildObject
{
}
Without annotation / Old Style
myChildObject.java
public class myChildObject implements myParentObject {
public boolean isInherited() {
return false;
}
public String doSomething() {
return "";
}
public boolean equals(Object obj) {
return false;
}
public int hashCode() {
return 0;
}
public String toString() {
return "";
}
public Class annotationType() {
return null;
}
}
Some Restriction |
- No annotation can inherit another.
- All methods declared by an annotation must be without parameters.
- it must return one of the following.
- a primitive type such as int, double
- an object of type String or Class
- an enum type
- Another annotation type
- an array of type
- an annotation cannot be generic.
Recent Comments