1 定义
注解(也被称为元数据)为我们在代码中添加额外信息提供了一种形式化的方法,使我们可以在稍后的某个时刻可以非常方便地使用这些数据。它为第三方工具提供了描述程序代码的注释信息。
2 注解原理
注解是代码的附属信息,它遵循一个基本原则:注解不能干扰程序代码的执行,无论删除还是添加注解,代码都必须正常运行。java语言解释器会忽略这些注解,而由第三方工具负责对注解进行处理。第三方工具可以利用代码的注解间接控制程序代码的运行,它们通过Java反射机制读取注解的信息,并且根据这些信息更改目标代码的逻辑。
3 代码实现
MyAnnotation.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) //注解保留到运行时,因此可以通过反射得到
@Target(ElementType.METHOD) //使用该注解的目标类型
public @interface MyAnnotation {
boolean value() default true; //注解成员
}
Examination.java
public class Examination {
@MyAnnotation(true)
public void admittedByschool(int score) {
System.out.println("需要监督");
}
@MyAnnotation(false)
public void leaveSchool(){
System.out.println("不需要监督");
}
}
TestMyAnnotation.java
import java.lang.reflect.Method;
public class TestMyAnnotation {
public static void main(String[] args) {
Class<?> examClazz=Examination.class;
Method[] methods=examClazz.getMethods();
for (Method method : methods) {
MyAnnotation annotation=method.getAnnotation(MyAnnotation.class);
if (annotation!=null) {
if(annotation.value()){
System.out.println(method.getName()+"(),需要被监督");
}else {
System.out.println(method.getName()+"(),不需要监督");
}
}
}
}
}
4 解释
下面的代码一目了然,不做多余的解释:
Retention.class
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
RetentionPolicy.class
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
Target.class
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
ElementType.class
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE
}