java.lang.reflect.Constructor.getParameterAnnotations() 方法示例



說明

java.lang.reflect.Constructor.getParameterAnnotations() 方法返回一個數組,表示由該 Constructor 物件表示的方法的正式引數上的註解,按宣告順序排列。(如果底層方法沒有引數,則返回一個長度為零的陣列。如果該方法有一個或多個引數,則為每個沒有註解的引數返回一個長度為零的巢狀陣列。)返回的陣列中包含的註解物件是可序列化的。此方法的呼叫方可以自由地修改返回的陣列;它不會影響返回給其他呼叫方的陣列。

宣告

以下是 java.lang.reflect.Constructor.getParameterAnnotations() 方法的宣告。

public Annotation[][] getParameterAnnotations()

返回

底層成員的簡單名稱。

示例

以下示例展示了 Java.lang.reflect.Constructor.getParameterAnnotations() 方法的使用。

Live Demo
package com.tutorialspoint;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;

public class ConstructorDemo {
   public static void main(String[] args) {

      Constructor[] constructors = SampleClass.class.getConstructors();
      Annotation[][] annotations = constructors[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 SampleClass(){
   }

   public SampleClass(@CustomAnnotation(name="sampleClassConstructor",  
      value = "Sample Constructor Annotation") String sampleField){
      this.sampleField = sampleField;
   }

   public String getSampleField() {
      return sampleField;
   }

   public void setSampleField(String sampleField) {
      this.sampleField = sampleField;
   } 
}

@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
   public String name();
   public String value();
}

讓我們編譯並執行以上程式,它將產生以下結果 -

name: sampleClassConstructor
value: Sample Constructor Annotation
java_reflect_constructor.htm
廣告
© . All rights reserved.