Java Class getAnnotations() 方法



描述

Java Class getAnnotations() 方法返回此元素上存在的所有註解。如果此元素沒有註解,則返回長度為零的陣列。此方法的呼叫者可以隨意修改返回的陣列;這不會影響返回給其他呼叫者的陣列。

宣告

以下是java.lang.Class.getAnnotations() 方法的宣告

public Annotation[] getAnnotations()

引數

返回值

此方法返回此元素上存在的所有註解。

異常

獲取類註解示例

以下示例顯示了 java.lang.Class.getAnnotations() 方法的用法。在這個程式中,我們建立了一個 ClassDemo 例項,然後使用 getClass() 方法檢索例項的類。使用 getAnnotations(),我們檢索了任何註解的陣列,然後列印它們。如果不存在註解,則相應地列印一條訊息。

package com.tutorialspoint;

import java.lang.annotation.Annotation;
   
public class ClassDemo {

   public static void main(String []args) {

      ClassDemo cls = new ClassDemo();
      Class c = cls.getClass();

      Annotation[] a = c.getAnnotations();
      if(a.length != 0) {
         for(Annotation val : a) {
            System.out.println(val.toString());
         }
      } else {
         System.out.println("Annotations is not present...");
      }
   }
} 

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Annotations is not present...

獲取 Thread 類註解示例

以下示例顯示了 java.lang.Class.getAnnotations() 方法的用法。在這個程式中,檢索 Thread 類的類。使用 getAnnotations(),我們檢索了任何註解的陣列,然後列印它們。如果不存在註解,則相應地列印一條訊息。

package com.tutorialspoint;

import java.lang.annotation.Annotation;
   
public class ClassDemo {

   public static void main(String []args) {
      Annotation[] a = Thread.class.getAnnotations();
      if(a.length != 0) {
         for(Annotation val : a) {
            System.out.println(val.toString());
         }
      } else {
         System.out.println("Annotations is not present...");
      }
   }
} 

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

Annotations is not present...
java_lang_class.htm
廣告
© . All rights reserved.