Java 元注解

元注解是指注解的注解,包括@Retention @Target @Document @Inherited四种。

1.@Retention: 定义注解的保留策略
@Retention(RetentionPolicy.SOURCE)   //注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
@Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到
首 先要明确生命周期长度 SOURCE < CLASS < RUNTIME ,所以前者能作用的地方后者一定也能作用。一般如果需要在运行时去动态获取注解信息,那只能用 RUNTIME 注解;如果要在编译时进行一些预处理操作,比如生成一些辅助代码(如 ButterKnife),就用 CLASS注解;如果只是做一些检查性的操作,比如 @Override 和 @SuppressWarnings,则可选用 SOURCE 注解。


2.@Target:定义注解的作用目标
源码为:
@Documented  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.ANNOTATION_TYPE)  
public @interface Target {  
    ElementType[] value();  
}  
@Target(ElementType.TYPE)   //接口、类、枚举、注解
@Target(ElementType.FIELD) //字段、枚举的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法参数
@Target(ElementType.CONSTRUCTOR)  //构造函数
@Target(ElementType.LOCAL_VARIABLE)//局部变量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包    
3.@Document:说明该注解将被包含在javadoc中
4.@Inherited:说明子类可以继承父类中的该注解
举例:

复制代码
// 适用类、接口(包括注解类型)或枚举  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.TYPE)  
public @interface ClassInfo {  
    String value();  
}  
    
// 适用field属性,也包括enum常量  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.FIELD)  
public @interface FieldInfo {  
    int[] value();  
}  
// 适用方法  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.METHOD)  
public @interface MethodInfo {  
    String name() default "long";  
    String data();  
    int age() default 27;  
}  
复制代码

这3个注解分别适用于不同的元素,并都带有不同的属性,在使用注解是需要设置这些属性值。
再定义一个测试类来使用这些注解:

复制代码
@ClassInfo("Test Class")  
public class TestRuntimeAnnotation {  
 
    @FieldInfo(value = {1, 2})  
    public String fieldInfo = "FiledInfo";  
 
    @FieldInfo(value = {10086})  
    public int i = 100;  
 
    @MethodInfo(name = "BlueBird", data = "Big")  
    public static String getMethodInfo() {  
        return TestRuntimeAnnotation.class.getSimpleName();  
    }  
}  
在代码中获取注解信息:
private void _testRuntimeAnnotation() {  
    StringBuffer sb = new StringBuffer();  
    Class<?> cls = TestRuntimeAnnotation.class;  
    Constructor<?>[] constructors = cls.getConstructors();  
    // 获取指定类型的注解  
    sb.append("Class注解:").append("\n");  
    ClassInfo classInfo = cls.getAnnotation(ClassInfo.class);  
    if (classInfo != null) {  
        sb.append(Modifier.toString(cls.getModifiers())).append(" ")  
                .append(cls.getSimpleName()).append("\n");  
        sb.append("注解值: ").append(classInfo.value()).append("\n\n");  
    }  
 
    sb.append("Field注解:").append("\n");  
    Field[] fields = cls.getDeclaredFields();  
    for (Field field : fields) {  
        FieldInfo fieldInfo = field.getAnnotation(FieldInfo.class);  
        if (fieldInfo != null) {  
            sb.append(Modifier.toString(field.getModifiers())).append(" ")  
                    .append(field.getType().getSimpleName()).append(" ")  
                    .append(field.getName()).append("\n");  
            sb.append("注解值: ").append(Arrays.toString(fieldInfo.value())).append("\n\n");  
        }  
    }  
 
    sb.append("Method注解:").append("\n");  
    Method[] methods = cls.getDeclaredMethods();  
    for (Method method : methods) {  
        MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);  
        if (methodInfo != null) {  
            sb.append(Modifier.toString(method.getModifiers())).append(" ")  
                    .append(method.getReturnType().getSimpleName()).append(" ")  
                    .append(method.getName()).append("\n");  
            sb.append("注解值: ").append("\n");  
            sb.append("name: ").append(methodInfo.name()).append("\n");  
            sb.append("data: ").append(methodInfo.data()).append("\n");  
            sb.append("age: ").append(methodInfo.age()).append("\n");  
        }  
    }  
 
    System.out.print(sb.toString());  

转载于:https://www.cnblogs.com/xuelin1221/p/10162417.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java自定义注解通常用于对注解进行注释和描述,其使用方法如下: 1. 定义一个注解,使用@Target、@Retention、@Documented三个注解注解进行描述。 2. 使用@Inherited注解,表示注解可以被继承。 3. 在需要使用注解的类、方法、属性等上面使用定义的注解,通过反射获取注解信息。 示例代码如下: @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface CustomAnnotation { String value() default ""; } 在需要使用注解的类、方法、属性等上面使用定义的注解: @CustomAnnotation(value = "这是一个自定义注解") public class Test { @CustomAnnotation(value = "这是一个字段注解") private String name; @CustomAnnotation(value = "这是一个方法注解") public void sayHello() { System.out.println("Hello World!"); } } 通过反射获取注解信息: Class testClass = Test.class; CustomAnnotation annotation1 = (CustomAnnotation) testClass.getAnnotation(CustomAnnotation.class); System.out.println(annotation1.value()); // 输出 "这是一个自定义注解" Field nameField = testClass.getDeclaredField("name"); CustomAnnotation annotation2 = nameField.getAnnotation(CustomAnnotation.class); System.out.println(annotation2.value()); // 输出 "这是一个字段注解" Method sayHelloMethod = testClass.getDeclaredMethod("sayHello"); CustomAnnotation annotation3 = sayHelloMethod.getAnnotation(CustomAnnotation.class); System.out.println(annotation3.value()); // 输出 "这是一个方法注解"

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值