当前位置: 首页 > news >正文

自定义注解的简单用法

自定义注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation {

    /**
     * 只使用一个变量是默认为value
     */
    String value() default "";

    /**
     * 注解的成员变量的类型是受限的,
     * 合法的类型包括:原始类型、String、Class、Annotation、Enum
     */
    int num() default 1;

}

元注解(对注解进行注解的注解):

  • @Target
ElementType.PACKAGE 包声明
ElementType.TYPE 类、接口声明
ElementType.CONSTRUCTOR 构造方法声明
ElementType.METHOD 方法声明
ElementType.FIELD 字段声明
ElementType.PARAMETER 参数声明
  • @Retention
RetentionPolicy.RUNTIME 运行时存在 可以通过反射获取
RetentionPolicy.CLASS 编译时存在 运行时忽略
RetentionPolicy.SOURCE 只在源码中显示 编译时丢弃
  • @Inherited
    允许子类继承

  • @Documented
    生成javadoc时会包含该注解


注解有传递性

解析

  1. 定义一个类
@MyAnnotation("userClass")
public class User {

    @MyAnnotation(value = "id annotation", num = 66)
    private Long id;

    private String name;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @MyAnnotation(value = "getName annotation")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  1. 解析
package morning.cat.annotation;

import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class AnnotationTest {


    @Test
    public void test1() {
        Class<User> clazz = User.class;
        // 获取类上注解
        Annotation[] annotationArr = clazz.getAnnotations();
        for (Annotation annotation : annotationArr) {
            if (annotation instanceof MyAnnotation) {
                MyAnnotation mya = (MyAnnotation) annotation;
                System.out.println(mya.value() + " - " + mya.num());
            }

        }
    }

    @Test
    public void test2() {
        Class<User> clazz = User.class;
        Method[] methods = clazz.getMethods();
        // 查找方法上的MyAnnotation注解
        // 方法1
        for (Method method : methods) {
            boolean flag = method.isAnnotationPresent(MyAnnotation.class);
            if (flag) {
                MyAnnotation mya = method.getAnnotation(MyAnnotation.class);
                System.out.println(mya.value() + " - " + mya.num());
                System.out.println();
            }
        }
        // 方法2
        for (Method method : methods) {
            Annotation[] annotations = method.getAnnotations();
            for (Annotation annotation : annotations) {
                if (annotation instanceof MyAnnotation) {
                    MyAnnotation mya = (MyAnnotation) annotation;
                    System.out.println(mya.value() + " - " + mya.num());
                }

            }
        }

    }

    @Test
    public void test3() {
        Class<User> clazz = User.class;

        // 获取私有变量
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            MyAnnotation mya = field.getAnnotation(MyAnnotation.class);
            if (mya != null) {
                System.out.println(mya.value() + " - " + mya.num());
            }
        }
    }
}

相关文章:

  • FreeBSD-STABLE 居然是开发用的分支,我一直搞错了好多年...!
  • Spring Data JPA 在 SpringBoot 应用中的简单实践
  • 心与心的交流
  • SimpleDateFormat 线程不安全案例
  • BPEL和JAVA(一篇不错的BPEL入门)
  • 关于 BlockingQueue 的一些认识及资料汇总
  • 欣闻我班上的学生林健在Image Cup比赛中取得好成绩
  • C#.NET常用函数大全
  • Java基本类型简介
  • 动态调用 WebService
  • 关于 ThreadPoolExecutor 的一些资料汇总及个人认识
  • ADO.NET数据操作摘录
  • 线程池ThreadPoolExecutor的拒绝策略
  • 关于 ScheduledThreadPoolExecutor 的一些资料汇总及个人理解
  • 无聊的事情真多
  • 【Leetcode】101. 对称二叉树
  • 77. Combinations
  • Android 初级面试者拾遗(前台界面篇)之 Activity 和 Fragment
  • chrome扩展demo1-小时钟
  • exif信息对照
  • FastReport在线报表设计器工作原理
  • JAVA SE 6 GC调优笔记
  • Java,console输出实时的转向GUI textbox
  • Mac转Windows的拯救指南
  • Python代码面试必读 - Data Structures and Algorithms in Python
  • 简单基于spring的redis配置(单机和集群模式)
  • 解决iview多表头动态更改列元素发生的错误
  • 前端存储 - localStorage
  • 如何优雅的使用vue+Dcloud(Hbuild)开发混合app
  • 入门到放弃node系列之Hello Word篇
  • 源码安装memcached和php memcache扩展
  • ​3ds Max插件CG MAGIC图形板块为您提升线条效率!
  • ​ssh-keyscan命令--Linux命令应用大词典729个命令解读
  • #FPGA(基础知识)
  • #Linux(帮助手册)
  • (二)Linux——Linux常用指令
  • (附源码)spring boot校园健康监测管理系统 毕业设计 151047
  • (附源码)springboot车辆管理系统 毕业设计 031034
  • (亲测成功)在centos7.5上安装kvm,通过VNC远程连接并创建多台ubuntu虚拟机(ubuntu server版本)...
  • (十八)三元表达式和列表解析
  • (四)搭建容器云管理平台笔记—安装ETCD(不使用证书)
  • (原创) cocos2dx使用Curl连接网络(客户端)
  • (转)fock函数详解
  • (转)原始图像数据和PDF中的图像数据
  • ***测试-HTTP方法
  • .locked1、locked勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .NET CF命令行调试器MDbg入门(一)
  • .Net CF下精确的计时器
  • .NET Core 2.1路线图
  • .NET CORE 3.1 集成JWT鉴权和授权2
  • .NET 表达式计算:Expression Evaluator
  • .net 发送邮件
  • .Net 应用中使用dot trace进行性能诊断
  • .NET连接MongoDB数据库实例教程
  • /bin/bash^M: bad interpreter: No such file or directory