自定义注解

一、注解基础

1.注解的定义

Java文件叫做Annotation,用@interface表示。

2.元注解 修饰注解的注解

@interface上面按需要注解上一些东西,包括@Retention、@Target、@Document、@Inherited四种。

@Retention 保留策略

@Retention(RetentionPolicy.SOURCE)   // 注解仅存在于源码中,在class字节码文件中不包含
@Retention(RetentionPolicy.CLASS)     // 默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
@Retention(RetentionPolicy.RUNTIME)  // 注解会在class字节码文件中存在,在运行时可以通过反射获取到

@Target 注解的作用目标:

@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)               // 包

注解包含在javadoc中:

@Documented

注解可以被继承:

@Inherited

3.注解解析器:用来解析自定义注解。

二、注解使用

案例一

自定义注解类

import java.lang.annotation.*;

@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface Init {
    public String value() default "null";
}

使用类

public class User {
    @Init("李三")
    public String name;
    @Init("23")
    public String arg;
}

解析
通过反射,获取自定义注解的值

import java.lang.reflect.Field;

public class Zhujie {
    public static void main(String[] args) {
        User user = new User();
        Field[] fields = User.class.getFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Init.class)) {
                Init annotation = field.getAnnotation(Init.class);
                String name = field.getName();
                String value = annotation.value();
                System.out.println("name = " + name + ", value = " + value);
                try {
                    field.set(user, annotation.value());
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("user = " + user.toString());
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。