Java注解Annotation使用方法归纳

简介

注解是从JDK5开始支持,是Java对元数据的一种特殊支持。与注释有一定区别,可以理解为代码上的特殊标记,通过这些标记我们可以在编译,类加载,运行等程序类的生命周期内被读取、执行相应的处理。通过注解开发人员可以在不改变原有代码和逻辑的情况下在源代码中嵌入补充信息。注解是Java语言的一种强大的功能。

自定义注解

1.编写自定义注解

  • 注解的定义修饰符为@interface
  • 注解中可以添加成员变量,成员变量以方法的形式定义
  • 需要使用@Retention注解来规定它的生命周期(编译期间、运行时等)
  • 需要使用@Target注解来规定它的适用范围(类型、方法、字段、方法参数等)

例子一

import java.lang.annotation.*;@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE,ElementType.ANNOTATION_TYPE})
public @interface TestAnnotation {String value();}

说明

  • @Inherited注解规定了这个自定义注解是可以被继承的。(父类修饰子类继承)
  • 注解定义中 String value(); 通过方法的方式定义了注解的成员变量value

使用注解进行修饰

  • 使用TestAnnotation来给类、成员变量添加注解
  • value命名的成员变量可以直接以参数的形式赋值。
@TestAnnotation("Class Student")
public class Student {@TestAnnotation("constance field")public static final String CLASS_NAME = "Student";@TestAnnotation("field")private String name;public Student(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}

例子二

  • 使用 default ${value} 的形式可以定义成员变量是否需要默认值。
import java.lang.annotation.*;@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE,ElementType.ANNOTATION_TYPE})
public @interface TestAnnotationTwo {String message();String[] names() default {};}

说明

  • 注解定义中 String message(); String[] names(); 通过方法的方式定义了注解的成员变量message和names,其中names为String数组

使用注解进行修饰

  • 非value命名的成员变量需要通过 fieldName = value 来进行赋值
  • 注解中可以为空(具有默认值)的成员变量可以不赋值
@TestAnnotationTwo(message = "Hello!")
public class StudentTwo {@TestAnnotationTwo(message = "Hi!", names = {"holo", "la"})private String id;@TestAnnotationTwo(message = "yes")private String name;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}

自定义注解处理

  • 一般定义好注解的生命周期、成员变量之后,还需要针对注解编写相应的处理程序,获取程序的元数据。

注解定义如下

import java.lang.annotation.*;@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.CONSTRUCTOR,ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE,ElementType.ANNOTATION_TYPE})
public @interface TestAnnotation {String value();
}

使用自定义注解修饰代码

  • 例子中的Student通过@TestAnnotation注解分别修饰了类、字段、方法以及方法参数
@TestAnnotation("Class Student")
public class Student {@TestAnnotation("constance field")public static final String CLASS_NAME = "Student";@TestAnnotation("field")private String name;@TestAnnotation("Constructor")public Student(String name) {this.name = name;}@TestAnnotation("getter")public String getName() {return name;}@TestAnnotation("setter")public void setName(String name) {this.name = name;}@TestAnnotation("public method")public void printName() {System.out.println(name);}@TestAnnotation("public method with parameter")public void printName(@TestAnnotation("parameter") String name) {System.out.println(name);}
}

编写处理程序获取元数据

  • 获取类(type)上的注解及其变量value值
public void learnClassAnnotation() {Class<?> clazzStudent = Student.class;for (Annotation annotation : clazzStudent.getAnnotations()) {if (annotation instanceof TestAnnotation) {System.out.println(((TestAnnotation) annotation).value());}if (annotation.annotationType() == TestAnnotation.class) {System.out.println(((TestAnnotation) annotation).value());}}
}
  • 结果如下
Class Student
Class Student
  • 获取字段(field)上的注解及其变量value值
public void learnFieldAnnotation() {Class<?> clazz = Student.class;List<Field> fields = Arrays.asList(clazz.getDeclaredFields());fields.forEach(field -> {System.out.println("\n\n------------------------field " + field.getName());for (Annotation annotation : field.getAnnotations()) {if (annotation instanceof TestAnnotation) {System.out.println(((TestAnnotation) annotation).value());}if (annotation.annotationType() == TestAnnotation.class) {System.out.println(((TestAnnotation) annotation).value());}}});}
  • 结果如下
------------------------field CLASS_NAME
constance field
constance field------------------------field name
field
field
  • 获取构造器(constructor)上的注解及其变量value值
public void learnConstructorAnnotation() {Class<?> clazz = Student.class;List<Constructor<?>> constructors = Arrays.asList(clazz.getDeclaredConstructors());constructors.forEach(constructor -> {System.out.println("\n\n------------------------constructor " + constructor.getName());for (Annotation annotation : constructor.getAnnotations()) {if (annotation instanceof TestAnnotation) {System.out.println(((TestAnnotation) annotation).value());}if (annotation.annotationType() == TestAnnotation.class) {System.out.println(((TestAnnotation) annotation).value());}}});
}
  • 结果如下
------------------------constructor Student
Constructor
Constructor
  • 获取方法(method)上的注解及其变量value值
public void learnMethodAnnotation() {Class<?> clazz = Student.class;List<Method> methods = Arrays.asList(clazz.getMethods());methods.forEach(method -> {System.out.println("\n\n------------------------method " + method.getName());for (Annotation annotation : method.getAnnotations()) {if (annotation instanceof TestAnnotation) {System.out.println(((TestAnnotation) annotation).value());}if (annotation.annotationType() == TestAnnotation.class) {System.out.println(((TestAnnotation) annotation).value());}}});
}
  • 结果如下
------------------------method getName
getter
getter------------------------method setName
setter
setter------------------------method printName
public method
public method------------------------method printName
public method with parameter
public method with parameter------------------------method wait------------------------method wait------------------------method wait------------------------method equals------------------------method toString------------------------method hashCode------------------------method getClass------------------------method notify------------------------method notifyAll
  • 获取方法参数(parameter)上的注解及其变量value值
public void learnParameterAnnotation() {Class<?> clazz = Student.class;List<Method> methods = Arrays.asList(clazz.getMethods());for (Method method : methods) {System.out.println("\n\n-----------------------------------------------method " + method.getName());for (Parameter parameter : method.getParameters()) {System.out.println("------------------------parameter " + parameter.getName());for (Annotation annotation : parameter.getAnnotations()) {if (annotation instanceof TestAnnotation) {System.out.println(((TestAnnotation) annotation).value());}if (annotation.annotationType() == TestAnnotation.class) {System.out.println(((TestAnnotation) annotation).value());}}}}
}
  • 结果
-----------------------------------------------method getName-----------------------------------------------method setName
------------------------parameter arg0-----------------------------------------------method printName-----------------------------------------------method printName
------------------------parameter arg0
parameter
parameter-----------------------------------------------method wait-----------------------------------------------method wait
------------------------parameter arg0
------------------------parameter arg1-----------------------------------------------method wait
------------------------parameter arg0-----------------------------------------------method equals
------------------------parameter arg0-----------------------------------------------method toString-----------------------------------------------method hashCode-----------------------------------------------method getClass-----------------------------------------------method notify-----------------------------------------------method notifyAll

说明

  • 通过反射方式获取Annotation[]数组之后,可以通过下面两种方式来判断此注解是否就是你自定义的注解

1.通过 instanceof 操作,判断annotation对象是否是自定义注解类

annotation instanceof TestAnnotation

2.通过 Annotation 的 annotationType() 方法获取到annotation对象的类型,并同自定义注解类进行比对

annotation.annotationType() == TestAnnotation.class

注解处理工具类

  • 最后附上注解处理的工具类,定义了若干实用的注解处理方法,希望对朋友们有所帮助
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;/*** Created by xuyh(Johnsonmoon) at 2018/1/3 11:43.*/
public class AnnotationUtils {/*** get declared annotations of the given class** @param clazz given class* @return annotations*/public static Annotation[] getAnnotations(Class<?> clazz) {return clazz.getAnnotations();}/*** get declared annotations of the given field** @param field given field* @return annotations*/public static Annotation[] getAnnotations(Field field) {return field.getAnnotations();}/*** get declared annotations of the given method** @param method given method* @return annotations*/public static Annotation[] getAnnotations(Method method) {return method.getAnnotations();}/*** get declared annotations of the given constructor** @param constructor given constructor* @return annotations*/public static Annotation[] getAnnotations(Constructor constructor) {return constructor.getAnnotations();}/*** get declared annotations of the given parameter** @param parameter given parameter* @return annotations*/public static Annotation[] getAnnotations(Parameter parameter) {return parameter.getAnnotations();}/*** Is field has annotation of annotationType** @param field          given field* @param annotationType given annotation type* @return true/false*/public static boolean hasAnnotation(Field field, Class<?> annotationType) {Annotation[] annotations = field.getAnnotations();if (annotations == null || annotations.length == 0)return false;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return true;}return false;}/*** Is clazz has annotation of annotationType** @param clazz          given clazz* @param annotationType given annotation type* @return true/false*/public static boolean hasAnnotation(Class<?> clazz, Class<?> annotationType) {Annotation[] annotations = clazz.getAnnotations();if (annotations == null || annotations.length == 0)return false;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return true;}return false;}/*** Is method has annotation of annotationType** @param method         given method* @param annotationType given annotation type* @return true/false*/public static boolean hasAnnotation(Method method, Class<?> annotationType) {Annotation[] annotations = method.getAnnotations();if (annotations == null || annotations.length == 0)return false;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return true;}return false;}/*** Is constructor has annotation of annotationType** @param constructor    given constructor* @param annotationType given annotation type* @return true/false*/public static boolean hasAnnotation(Constructor<?> constructor, Class<?> annotationType) {Annotation[] annotations = constructor.getAnnotations();if (annotations == null || annotations.length == 0)return false;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return true;}return false;}/*** Is parameter has annotation of annotationType** @param parameter      given parameter* @param annotationType given annotation type* @return true/false*/public static boolean hasAnnotation(Parameter parameter, Class<?> annotationType) {Annotation[] annotations = parameter.getAnnotations();if (annotations == null || annotations.length == 0)return false;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return true;}return false;}/*** Get annotation of given annotation type declared in given field.** @param field          given field* @param annotationType given annotation type* @return annotation instance*/public static Annotation getAnnotation(Field field, Class<?> annotationType) {Annotation[] annotations = field.getAnnotations();if (annotations == null || annotations.length == 0)return null;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return annotation;}return null;}/*** Get annotation of given annotation type declared in given clazz.** @param clazz          given clazz* @param annotationType given annotation type* @return annotation instance*/public static Annotation getAnnotation(Class<?> clazz, Class<?> annotationType) {Annotation[] annotations = clazz.getAnnotations();if (annotations == null || annotations.length == 0)return null;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return annotation;}return null;}/*** Get annotation of given annotation type declared in given method.** @param method         given method* @param annotationType given annotation type* @return annotation instance*/public static Annotation getAnnotation(Method method, Class<?> annotationType) {Annotation[] annotations = method.getAnnotations();if (annotations == null || annotations.length == 0)return null;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return annotation;}return null;}/*** Get annotation of given annotation type declared in given constructor.** @param constructor    given constructor* @param annotationType given annotation type* @return annotation instance*/public static Annotation getAnnotation(Constructor<?> constructor, Class<?> annotationType) {Annotation[] annotations = constructor.getAnnotations();if (annotations == null || annotations.length == 0)return null;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return annotation;}return null;}/*** Get annotation of given annotation type declared in given parameter.** @param parameter      given parameter* @param annotationType given annotation type* @return annotation instance*/public static Annotation getAnnotation(Parameter parameter, Class<?> annotationType) {Annotation[] annotations = parameter.getAnnotations();if (annotations == null || annotations.length == 0)return null;for (Annotation annotation : annotations) {if (annotation.annotationType() == annotationType)return annotation;}return null;}
}

Java 注解(Annotation)使用方法归纳相关推荐

  1. Java注解(Annotation)详解

    转: Java注解(Annotation)详解 幻海流心 2018.05.23 15:20 字数 1775 阅读 380评论 0喜欢 1 Java注解(Annotation)详解 1.Annotati ...

  2. Java注解Annotation 完成验证

    Java注解Annotation用起来很方便,也越来越流行,由于其简单.简练且易于使用等特点,很多开发工具都提供了注解功能,不好的地方就是代码入侵比较严重,所以使用的时候要有一定的选择性. 这篇文章将 ...

  3. java注释和注解_深入理解JAVA注解(Annotation)以及自定义注解

    Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制.Java 语言中的类.方法.变量.参数和包等都可以被标注.注解可以看作是一种特殊的标记,在程序在编译或 ...

  4. java 注解: Annotation

    java 注解: Annotation 普通注解 自定义注解 元注解 注解: 位于源码中,用来修饰程序的元素,但不会对被修饰的对象有直接的影响. 可增加程序的动态性. 普通注解 普通注解:为java代 ...

  5. Java注解annotation invalid type of annotation member

    文章目录 Java注解annotation : invalid type of annotation member 1.什么是invalid type of annotation member 2.哪 ...

  6. 深入理解Java注解Annotation之注解处理器

    如果没有用来读取注解的方法和工作,那么注解也就不会比注释更有用处了.使用注解的过程中,很重要的一部分就是创建于使用注解处理器.Java SE5扩展了反射机制的API,以帮助程序员快速的构造自定义注解处 ...

  7. 深入理解Java注解Annotation及自定义注解

    要深入学习注解,我们就必须能定义自己的注解,并使用注解,在定义自己的注解之前,我们就必须要了解Java为我们提供的元注解和相关定义注解的语法. 元注解: 元注解的作用就是负责注解其他注解.Java5. ...

  8. Java注解Annotation的基本概念

    什么是注解(Annotation): Annotation(注解)就是Java提供了一种元程序中的元素关联任何信息和着任何元数据(metadata)的途径和方法.Annotion(注解)是一个接口,程 ...

  9. Java注解Annotation详解

    注解相当于一种标记,在程序中加了注解就等于为程序打上了某种标记,没加,则等于没有某种标记,以后,javac编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有无何种标记,看你有什么标记,就去 ...

最新文章

  1. 【移动端最强架构】LCNet吊打现有主流轻量型网络(附代码实现)
  2. mysql主从(GTID复制模式)
  3. 51nod 1105:第K大的数
  4. 2020-12-11 Python yield 使用浅析
  5. 程序语言(编程语言)汇总大全
  6. 基于VSM的命名实体识别、歧义消解和指代消解
  7. Trie实现(C++)
  8. spark学习-SparkSQL-java版JavaRDD与JavaPairRDD的互相转换
  9. golang []byte和string相互转换
  10. c语言全面,最新版c语言经典习题100例(最全面).doc
  11. 自强学堂mysql_Django ——自强学堂学习笔记
  12. 使用ensp搭建简单校园网拓扑
  13. 没有CUE的情况下APE刻录CD
  14. 从0到1 激活函数(一)sigmod函数
  15. 【参赛作品66】快速搭建一套openGauss主备高可用集群
  16. beyond compare下载安装及使用教程
  17. 终结者外传第二季大结局剧情及评论
  18. 机器人总动员片尾曲歌词_机器人瓦力 主题曲 很感人的那首歌 叫什么名字
  19. Ubuntu的商业模式
  20. yo搭建nodejs项目脚手架

热门文章

  1. 4、构建 Instrumented 单元测试
  2. sql还原mysql_sql 数据库还原图文教程
  3. centos安装anaconda教程
  4. java 解析xml 对象_Java反射——读取XML文件,创建对象
  5. bootstrap-table和bootstrap-switch
  6. 用友NC软件被locked1勒索病毒攻击加密的方式,服务器oracle数据库中了勒索病毒
  7. HTML表格(table、tr、td、th、thead、tbody、tfoot标签)
  8. 2020年公认最好一篇文章,必看
  9. 智能语音电话机器人的语音识别是如何实现的?
  10. 02_d2-分类算法概述