天天看点

方法参数的注释

可以先获得方法的参数注释集合:

第二维[]代表的是方法参数附带的具体的注释Annotation的类。

通过annotations.length可以获取方法参数的数量

通过annotations[i].length可以获取某一个参数中,带有的注释的数量。

当参数中某一个参数不存在任何注释Annotation时,直接检查注释Annotation的类会报集合异常,因此需要手工检查:方法是必须确保数组的第一维的二维长度不能为0。

if(annotations[i].length > 0){

在此可以安全地获取注释了

.....

}

获取具体某一个参数的注释后,需要用比较法,才能确定该注释的具体类型,然后将其窄化后才能够提取注释本身的参数值;

如下例,将提取在App类中的构造器参数上施加的注释:

public static void main(String[] args) {

Class app = App.class;

Constructor constructor = app.getConstructors()[0];

Annotation[][] annotations = constructor.getParameterAnnotations();

 for (int i = 0; i < annotations.length; i++) {

if (annotations[i][0] instanceof COUNT) {

System.out.println(((COUNT) annotations[i][0]).value());

其中,假设@COUNT为可在方法参数上使用的注释,并带有一个Stirng类型的参数value

继续阅读