- Java Annotation is a tag that represents the metadata i.e. attached with class, interface, methods or fields to indicate some additional information which can be used by java compiler and JVM.
- Annotations in Java are used to provide additional information, so it is an alternative option for XML and Java marker interfaces.
Creating Custom Annotation in java
- Marker Annotation.
- Single Value Annotation.
- Multi Value Annotation
Below is the Example of Multi Value Annotation :
package com.annotation.demo;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited // Annotation will be available to all child classes
@Documented // Annotation will be available in the documentation
@Target(ElementType.TYPE) //Type - Annotation on class
@Retention(RetentionPolicy.RUNTIME) // Annotation avialability (SOURCE,CLASS,RUNTIME)
@interface Bird{
String name() default "Bird";
boolean doesFly() default true;
}
@Bird(name="Hedwig",doesFly=true)
class Owl{
boolean nocternal;
boolean rotate360;
public Owl(boolean nocternal, boolean rotate360) {
this.nocternal = nocternal;
this.rotate360 = rotate360;
}
}
public class AnnotationDemo3 {
public static void main(String[] args) {
Owl owl = new Owl(true,true);
Class c = owl.getClass();
Annotation an = c.getAnnotation(Bird.class);
Bird bird = (Bird)an;
System.out.println(bird.name());
System.out.println("Can bird fly ? "+bird.doesFly());
}
}
Output :