- @Target解读
- @Retention解读
- @Document解读
- @Inherited
- 定义注解
import java.lang.annotation.*;
/**
* desc: 自定义注解
*
* @author qts
* @date 2022/4/21 0021
*/
@Documented
// 此处改一下,指定使用在什么地方 (类,方法,类属性 ...) 参考如下@Target解读
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface MyAnnotation {
String value() default "";
String myValue() default "我是自定义注解";
}
- 使用自定义注解
@MyAnnotation(value = "默认value")
public class TestAnnotation {
public static void main(String[] args) {
TestAnnotation testAnnotation = new TestAnnotation();
Class extends TestAnnotation> aClass = testAnnotation.getClass();
if (aClass.isAnnotationPresent(MyAnnotation.class)) {
System.out.println("TestAnnotation类上配置了 MyAnnotation注解 !");
MyAnnotation annotation = aClass.getAnnotation(MyAnnotation.class);
System.out.println("value:" + annotation.value() +"; myValue:" + annotation.myValue());
}
testMethodAspect();
}
}
- 执行结果
Target类型 | 描述 |
---|---|
ElementType.TYPE | 应用于类、接口(包括注解类型)、枚举 |
ElementType.FIELD | 应用于属性(包括枚举中的常量) |
ElementType.METHOD | 应用于方法 |
ElementType.PARAMETER | 应用于方法的形参 |
ElementType.CONSTRUCTOR | 应用于构造函数 |
ElementType.LOCAL_VARIABLE | 应用于局部变量 |
ElementType.ANNOTATION_TYPE | 应用于注解类型 |
ElementType.PACKAGE | 应用于包 |
ElementType.TYPE_PARAMETER | 1.8版本新增,应用于类型变量 |
ElementType.TYPE_USE | 1.8版本新增,应用于任何使用类型的语句中(例如声明语句、泛型和强制转换语句中的类型) |
表明该注解的生命周期
生命周期类型 | 描述 |
---|---|
RetentionPolicy.SOURCE | 编译时被丢弃,不包含在类文件中 |
RetentionPolicy.CLASS | JVM加载时被丢弃,包含在类文件中,默认值 |
RetentionPolicy.RUNTIME | 由JVM 加载,包含在类文件中,在运行时可以被获取到 |
表明该注解标记的元素可以被Javadoc 或类似的工具文档化。
@Inherited表明使用了@Inherited注解的注解,所标记的类的子类也会拥有这个注解。
出处 https://www.cnblogs.com/dw3306/p/15786126.html
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)