自定义注解的学习与使用

1.元注解

 首先我们想要定义自己的注解类,必须先了解元注解.一般要实现自己的注解类,那就需要了解一些常用的元注解.

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

@Retention:注解的保留位置

RetentionPolicy.SOURCE:这种类型的Annotations只在源代码级别保留,编译时就会被忽略,在class字节码文件中不包含。
RetentionPolicy.CLASS:这种类型的Annotations编译时被保留,默认的保留策略,在class文件中存在,但JVM将会忽略,运行时无法获得。
RetentionPolicy.RUNTIME:这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用。
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解

2.注解类的创建

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Name {
    public String value() default "";
}

3.使用类创建

public class Student {
    @Name("xiaoming")
    private String name;

    public String getName() {
        setAnnotation();
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    //通过反射获取注解类的信息
    private void setAnnotation(){
        Class<? extends Student> clazz = this.getClass();
        //判断处理注解在类上
        if (clazz.isAnnotationPresent(Name.class)) {
            //获取注解类
            Name annotation = (Name) clazz.getAnnotation(Name.class);
            try {
                //设值
                Field field = clazz.getDeclaredField("name");
                field.setAccessible(true);
                field.set(this, annotation.value());
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return;
        }
        //判断处理注解在属性上
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            Name annotation = declaredField.getAnnotation(Name.class);
            if (null == annotation) {
                continue;
            }
            declaredField.setAccessible(true);
            try {
                declaredField.set(this, annotation.value());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}

4.运行测试

main方法执行

 Student s = new Student();
 System.out.println(s.getName());

运行结果:

 

 

以上纯粹是为了测试注解类的使用,实际生产中还是要根据自己的情况去使用自定义注解,如有错误,欢迎指出,谢谢.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值