入门
1. 定义
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String value() default "defaultValue";
}
@Target
: 指定注解的使用范围; ElementType 枚举 TYPE, FIELD,METHOD…
@Retention
: 指示带注释类型的注释将保留多长时间。默认: @Retention 上的 @Retention(RetentionPolicy.RUNTIME); RetentionPolicy 枚举 CLASS\RUNTIME\SOURCE
2. 使用
import com.yang.annotation.MyAnnotation;
@MyAnnotation("value")
public class Entity() {
}
3. 获取注解内容
通过反射获取注解内变量的值
import com.yang.annotation.MyAnnotation;
import javax.swing.text.html.parser.Entity;
public class Test {
void content() {
System.out.println(Entity.class.getAnnotation(MyAnnotation.class).value());
}
}
获取注解的方法
对应 ElementType的 TYPE\FIELD\METHOD
- TYPE (Class 类下)
getAnnotation(Class annotationClass) - 获取指定类型的注解 , 无返回 null
getAnnotations() - 返回所有注解
getAnnotationsByType(Class annotationClass)
Returns annotations that are associated with this element.
- Field
getAnnotatedType()
Returns an AnnotatedType object that represents the use of a type to specify the declared type of the field represented by this Field.
getAnnotation(Class annotationClass)
Returns this element’s annotation for the specified type if such an annotation is present, else null.
getAnnotationsByType(Class annotationClass)
Returns annotations that are associated with this element.
- METHOD
getAnnotatedReturnType()
Returns an AnnotatedType object that represents the use of a type to specify the return type of the method/constructor represented by this Executable.
getAnnotation(Class annotationClass)
Returns this element’s annotation for the specified type if such an annotation is present, else null.
getDeclaredAnnotations() - 返回元素注解列表
Returns annotations that are directly present on this element.
4. 输出内容
value