Java 包 isAnnotationPresent() 方法



描述

Java 包 isAnnotationPresent(Class<? extends Annotation> annotationClass) 方法返回 true,如果此元素上存在指定型別的註釋,否則返回 false。此方法主要用於方便地訪問標記註釋。

宣告

以下是 java.lang.Package.isAnnotationPresent() 方法的宣告

public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)

引數

annotationClass − 與註釋型別對應的 Class 物件

返回值

如果此元素上存在指定註釋型別的註釋,則此方法返回 true,否則返回 false

異常

NullPointerException − 如果給定的註釋類為空

示例

以下示例演示了 isAnnotationPresent() 方法的用法。在這個程式中,我們聲明瞭一個註釋 Demo,它是一個介面,帶有一個返回字串的方法和另一個返回整數值的方法。在 PackageDemo 類中,我們在一個名為 example() 的方法上應用了該 Demo 註釋,並賦予了一些值。在 example() 方法中,我們使用 getClass() 方法檢索了 PackageDemo 類的類。

現在使用 getMethod() example,我們檢索 example 方法例項,然後使用 getAnnotation() 方法檢索註釋並列印其值。在主方法中,呼叫此 example() 方法並列印結果。

然後,使用 getPackages() 方法檢索所有包,並迭代它們以使用 isAnnotationPresent() 方法檢查 Demo 註釋是否存在,並列印結果。

package com.tutorialspoint;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;

// declare a new annotation
@Retention(RetentionPolicy.RUNTIME)
@interface Demo {
   String str();
   int val();
}

public class PackageDemo {

   // set values for the annotation
   @Demo(str = "Demo Annotation", val = 100)
   
   // a method to call in the main
   public static void example() {
      PackageDemo ob = new PackageDemo();
      
      try {
         Class c = ob.getClass();

         // get the method example
         Method m = c.getMethod("example");

         // get the annotation for class Demo
         Demo annotation = m.getAnnotation(Demo.class);

         // print the annotation
         System.out.println(annotation.str() + " " + annotation.val());
      } catch (NoSuchMethodException exc) {
         exc.printStackTrace();
      }
   }

   public static void main(String args[]) {
      example();

      Package[] pack = Package.getPackages();
   
      // check if annotation Demo exists
      for (int i = 0; i < pack.length; i++) {
         System.out.println("" + pack[i].isAnnotationPresent(Demo.class));
      }
   }
}

輸出

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

Demo Annotation 100
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
false
java_lang_package.htm
廣告
© . All rights reserved.