java.lang.reflect.Method.getParameterAnnotations() 方法示例
描述
java.lang.reflect.Method.getParameterAnnotations() 方法返回一个数组,该数组按声明顺序表示此 Method 对象所表示方法的形式参数上的注释。(如果底层方法无参数,则返回长度为零的数组。如果方法有一个或多个参数,则为每个没有注释的参数返回一个长度为零的嵌套数组。)返回的数组中包含的注释对象是可序列化的。此方法的调用者可以自由修改返回的数组;它不会对返回给其他调用者的数组产生任何影响。
声明
以下是 java.lang.reflect.Method.getParameterAnnotations() 方法的声明。
public Annotation[][] getParameterAnnotations()
返回
底层成员的简单名称。
示例
以下示例显示了 java.lang.reflect.Method.getParameterAnnotations() 方法的用法。
package com.tutorialspoint; import java.lang.annotation.Annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Method; public class MethodDemo { public static void main(String[] args) { Method[] methods = SampleClass.class.getMethods(); Annotation[][] annotations = methods[1].getParameterAnnotations(); for(Annotation[] annotation1 : annotations){ for(Annotation annotation : annotation1){ if(annotation instanceof CustomAnnotation){ CustomAnnotation customAnnotation = (CustomAnnotation) annotation; System.out.println("name: " + customAnnotation.name()); System.out.println("value: " + customAnnotation.value()); } } } } } @CustomAnnotation(name = "SampleClass", value = "Sample Class Annotation") class SampleClass { private String sampleField; public String getSampleField() { return sampleField; } public void setSampleField(@CustomAnnotation(name="sampleClassMethod", value = "Sample Method Annotation") String sampleField) { this.sampleField = sampleField; } } @Retention(RetentionPolicy.RUNTIME) @interface CustomAnnotation { public String name(); public String value(); }
让我们编译并运行上述程序,这将产生以下结果 −
name: sampleClassMethod value: Sample Method Annotation