Java自定义Annotation并通过反射解析Annotation

深藏阁楼爱情的钟 2022-04-25 10:44 227阅读 0赞

一. 引言

对于使用过Spring的人来说,注解并不陌生,之前也写过一篇文章,介绍过注解。

https://blog.csdn.net/zxd1435513775/article/details/89973721

二. 自定义注解

1. 创建一个自定义的Annotation

  1. @Documented
  2. @Target(ElementType.METHOD) // 表明该注解只能用于修饰方法
  3. @Retention(RetentionPolicy.RUNTIME) // 该注解会在运行时有效(即运行时保留)
  4. public @interface MethodInfo {
  5. // 以下是属性方法
  6. String author() default "dada";
  7. String version() default "1.0";
  8. String date();
  9. String comment();
  10. }
  • @Target作用:用于描述注解的使用范围(即:被描述的注解可以用在什么地方)

    @Target说明了Annotation所修饰的对象范围:Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。

@Target取值(ElementType)有:

​ 1.CONSTRUCTOR: 用于描述构造器
​ 2.FIELD: 用于描述域
​ 3.LOCAL_VARIABLE: 用于描述局部变量
​ 4.METHOD: 用于描述方法
​ 5.PACKAGE: 用于描述包
​ 6.PARAMETER: 用于描述参数
​ 7.TYPE: 用于描述类、接口(包括注解类型) 或enum声明

  • @Retention作用:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)

    @Retention定义了该Annotation被保留的时间长短:某些Annotation仅出现在源代码中,当源代码被编译器编译时,这些注解会被编译器丢弃,并不会出现在class文件中;而有一些却能被编译编译到class文件中;编译在class文件中的Annotation可能会被虚拟机忽略,而另一些在class被装载时将被读取(请注意并不影响class的执行,因为Annotation与class在使用上是被分离的)。使用这个meta-Annotation可以对 Annotation的“生命周期”限制。

@Retention取值(RetentionPoicy)有:

​ 1.SOURCE: 在源文件中有效(即源文件保留)
​ 2.CLASS: 在class文件中有效(即class保留)
​ 3.RUNTIME: 在运行时有效(即运行时保留)

  • @Documented

    @Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。

  • @Inherited:

    @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。则这个annotation将被用于该class的子类。

注意:@Inherited annotation类型是被标注过的class的子类所继承。类并不从它所实现的接口继承annotation,方法并不从它所重载的方法继承annotation。

2. Java 内置的Annotation

从Java5版本开始,自带了三种标准annontation类型。

Override,java.lang.Override 是一个marker annotation类型,它被用作标注方法。它说明了被标注的方法重载了父类的方法,起到了断言的作用。如果我们使用了这种annotation在一个没有覆盖父类方法的方法时,java编译器将以一个编译错误来警示。这个annotaton常常在我们试图覆盖父类方法而确又写错了方法名时加一个保障性的校验过程。

Deprecated,Deprecated也是一种marker annotation。编译器将不鼓励使用这个被标注的程序元素。所以使用这种修饰具有一定的 “延续性”:如果我们在代码中通过继承或者覆盖的方式使用了这个过时的类型或者成员,虽然继承或者覆盖后的类型或者成员并不是被声明为 @Deprecated,但编译器仍然要报警。注意:@Deprecated这个annotation类型和javadoc中的 @deprecated这个tag是有区别的:前者是java编译器识别的,而后者是被javadoc工具所识别用来生成文档。

SuppressWarnings,此注解能告诉Java编译器关闭对类、方法及成员变量的警告。有时编译时会提出一些警告,对于这些警告有的隐藏着Bug,有的是无法避免的,对于某些不想看到的警告信息,可以通过这个注解来屏蔽。SuppressWarning不是一个marker annotation。它有一个类型为String[]的成员,这个成员的值为被禁止的警告名。对于javac编译器来讲,同时编译器忽略掉无法识别的警告名。

下面来使用下Java内置的 Annotation 和 自定义的Annotation

  1. public class AnnotationExample {
  2. @Override
  3. @MethodInfo(author = "scorpios",version = "1.0",date = "2019/10/20",comment = "aaaa")
  4. public String toString() {
  5. return "AnnotationExample{}";
  6. }
  7. }

使用反射来解析Annotation

注意:Annotation的Retention Policy 必须是RUNTIME,否则我们无法在运行时从该类里面获得任何数据

  1. public class AnnotationParser {
  2. public static void main(String[] args) {
  3. // 获取类中的所有方法,并循环遍历每一个方法
  4. for (Method method: AnnotationExample.class.getMethods()) {
  5. // 判断方法是否标注MethodInfo注解
  6. if (method.isAnnotationPresent(MethodInfo.class)) {
  7. // 拿到注解信息,并遍历注解里面的数据
  8. for (Annotation annotation:method.getAnnotations()) {
  9. System.out.println("------------------------");
  10. System.out.println(annotation + " works on method:"+ method);
  11. }
  12. MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);
  13. System.out.println(methodInfo);
  14. System.out.println(methodInfo.author());
  15. System.out.println(methodInfo.comment());
  16. System.out.println(methodInfo.date());
  17. System.out.println(methodInfo.version());
  18. }
  19. }
  20. System.out.println("--------------反射调用方法---------------");
  21. try {
  22. AnnotationExample example = new AnnotationExample();
  23. Class clazz = example.getClass();
  24. Method method = clazz.getDeclaredMethod("toString");
  25. String result = (String) method.invoke(example);
  26. System.out.println(result);
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. }

输出结果:
在这里插入图片描述

三. 利用自定义注解自动生成查询SQL

  1. @Entity("city")
  2. public class City {
  3. private Integer id;
  4. private String name;
  5. public Integer getId() {
  6. return id;
  7. }
  8. public void setId(Integer id) {
  9. this.id = id;
  10. }
  11. public String getName() {
  12. return name;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. }
  18. public class CommonUtil {
  19. public static String buildQuerySqlForEntity(Object object){
  20. String sql = "select * from ";
  21. Class clazz = object.getClass();
  22. // 判断是否有注解
  23. if(clazz.isAnnotationPresent(Entity.class)){
  24. // 得到注解
  25. Entity entity = (Entity) clazz.getAnnotation(Entity.class);
  26. // 调用属性方法
  27. String value = entity.value();
  28. sql = sql + value;
  29. }
  30. return sql;
  31. }
  32. }
  33. @Target(ElementType.TYPE)
  34. @Retention(RetentionPolicy.RUNTIME)
  35. public @interface Entity {
  36. public String value() default "";
  37. }
  38. public static void main( String[] args ) {
  39. City city = new City();
  40. city.setId(1);
  41. city.setName("nanjing");
  42. String sql = CommonUtil.buildQuerySqlForEntity(city);
  43. System.out.println(sql);
  44. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,227人围观)

还没有评论,来说两句吧...

相关阅读