java.lang.reflect.Method.getParameterAnnotations()
方法返回一個陣列陣列,它們以宣告順序表示由此Method
物件表示的方法的形式引數的註釋(如果底層方法是無引數的,則返回一個長度為零的陣列,如果該方法具有一個或多個引數,則對於每個沒有註釋的引數,返回長度為零的巢狀陣列)。返回的陣列中包含的註釋物件是可序列化的。該方法的呼叫者可以自由修改返回的陣列; 它將對返回給其他呼叫者的陣列沒有影響。
以下是java.lang.reflect.Method.getParameterAnnotations()
方法的宣告。
public Annotation[][] getParameterAnnotations()
引數
返回值
Method
物件表示的方法的形式引數的注釋。異常
以下範例顯示java.lang.reflect.Method.getParameterAnnotations()
方法的用法。
package com.yiibai;
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