Java Tutorial/Language/Annotations Create
Содержание
Creating Annotations
Annotation is created based on the interface.
- Adding "@" before the keyword interface to declare an annotation type.
- All annotations consist only method declarations.
- These methods act much like fields.
Our first annotation type:
// A simple annotation type.
@interface MyAnnotation {
String stringValue();
int intValue();
}
default values in an annotation.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str() default "Testing";
int val() default 9000;
}
class Meta3 {
@MyAnno()
public static void myMeth() {
Meta3 ob = new Meta3();
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();
}
}
Define new annotation type
- All annotation types automatically extend the Annotation interface.
- Annotation is a super-interface of all annotations.
- It overrides hashCode( ), equals( ), and toString() defined by Object.
- It defines annotationType( ), which returns a Class object that represents the invoking annotation.
- When you apply an annotation, you give values to its members.
// A simple annotation type.
@interface MyAnnotation {
String stringValue();
int intValue();
}
public class MainClass {
// Annotate a method.
@MyAnnotation(stringValue = "Annotation Example", intValue = 100)
public static void myMethod() {
}
}
Specifying a Retention Policy
A retention policy determines at what point an annotation is discarded.
- SOURCE: annotation retained only in the source file and is discarded during compilation.
- CLASS: annotation stored in the .class file during compilation, not available in the run time.
- RUNTIME: annotation stored in the .class file and available in the run time.
- They are defined java.lang.annotation.RetentionPolicy enumeration.
A retention policy is specified using Java"s built-in annotations: @Retention.
@Retention(retention-policy)