当前位置: 移动技术网 > IT编程>开发语言>Java > Java注解与反射原理说明

Java注解与反射原理说明

2019年07月19日  | 移动技术网IT编程  | 我要评论

一 点睛

注解若想发挥更大作用,还需借助反射机制之力。通过反射,可以取得一个方法上声明的注解的全部内容。

一般有两种需求:

1 取得方法中全部的注解,通过调用getannotations来实现。

2 判断操作是否是指定注解,通过调用getannotation来实现。

下面从源码角度来说明怎样获取这些注解信息。

二 源码导读——取得方法中全部的注解

public class accessibleobject implements annotatedelement {
  ...
  //取得全部annotation
  public annotation[] getannotations() {
    return getdeclaredannotations();
  }  
  ...
}
public final class method extends executable {
  ...
  public annotation[] getdeclaredannotations() {
    //针对method类,需要调用父类的getdeclaredannotations方法
    return super.getdeclaredannotations();
  }  
  ...
}
//method的父类executable的getdeclaredannotations实现全部注解信息的获取
public abstract class executable extends accessibleobject
  implements member, genericdeclaration {
  ...
  public annotation[] getdeclaredannotations() {
    return annotationparser.toarray(declaredannotations());
  }  
  ...
}

三 源码导读——判断操作是否是指定注解

public final class method extends executable {
  ...
  ////取得指定annotation
  public <t extends annotation> t getannotation(class<t> annotationclass) {
    return super.getannotation(annotationclass);
  }
  ...
}
public abstract class executable extends accessibleobject
  implements member, genericdeclaration {
  ...
  public <t extends annotation> t getannotation(class<t> annotationclass) {
    objects.requirenonnull(annotationclass);
    //获得指定注解类的信息
    return annotationclass.cast(declaredannotations().get(annotationclass));
  }  
  ...
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网