描述
這個java.lang.reflect.AccessibleObject.getAnnotations()方法返回此元素上存在的所有注釋。 (如果此元素沒有注釋,則返回長度為零的數組。)此方法的調用者可以自由修改返回的數組;它不會影響返回給其他調用者的數組。
聲明
以下是聲明java.lang.reflect.AccessibleObject.getAnnotations()方法。
public Annotation[] getAnnotations()
返回值
此元素上存在的所有注釋。
示例
下麵的例子展示了 java.lang.reflect.AccessibleObject.getAnnotations() 方法的用法。
現場演示package com.tutorialspoint;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
public class AccessibleObjectDemo {
   public static void main(String[] args) throws NoSuchMethodException, 
      SecurityException, NoSuchFieldException {
      AccessibleObject sampleMethod = SampleClass.class.getMethod("sampleMethod");
      Annotation[] annotations = sampleMethod.getAnnotations();
      for(Annotation annotation:annotations){
         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;
   @CustomAnnotation(name = "sampleMethod",  value = "Sample Method Annotation")
   public String sampleMethod(){
      return "sample";
   }
   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:sampleMethod value:Sample Method Annotation
相關用法
- Java java.lang.reflect.AccessibleObject.getAnnotation()用法及代碼示例
 - Java java.lang.reflect.AccessibleObject.getDeclaredAnnotations()用法及代碼示例
 - Java java.lang.reflect.AccessibleObject.setAccessible()用法及代碼示例
 - Java java.lang.reflect.AccessibleObject.isAccessible()用法及代碼示例
 - Java java.lang.reflect.Array.get()用法及代碼示例
 - Java java.lang.reflect.Array.getChar()用法及代碼示例
 - Java java.lang.reflect.Array.getInt()用法及代碼示例
 - Java java.lang.reflect.Array.getFloat()用法及代碼示例
 - Java java.lang.reflect.Array.getByte()用法及代碼示例
 - Java java.lang.reflect.Array.getDouble()用法及代碼示例
 - Java java.lang.reflect.Array.getLong()用法及代碼示例
 - Java java.lang.reflect.Array.setLong()用法及代碼示例
 - Java java.lang.reflect.Array.getLength()用法及代碼示例
 - Java java.lang.reflect.Array.set()用法及代碼示例
 - Java java.lang.reflect.Array.setInt()用法及代碼示例
 - Java java.lang.reflect.Array.getBoolean()用法及代碼示例
 - Java java.lang.reflect.Array.setShort()用法及代碼示例
 - Java java.lang.reflect.Array.setChar()用法及代碼示例
 - Java java.lang.reflect.Array.getShort()用法及代碼示例
 
注:本文由純淨天空篩選整理自 java.lang.reflect.AccessibleObject.getAnnotations() Method Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
