Java Package.getAnnotation()方法


Java Package.getAnnotation()方法用法實例教程。返回該元素的指定類型的注釋,如果是這樣的注釋,否則返回null。
 
 

描述

java.lang.Package.getAnnotation(Class<A> annotationClass) 方法返回該元素的指定類型的注釋,如果是這樣的注釋,否則返回null。

聲明

以下是java.lang.Package.getAnnotation()方法的聲明

public <A extends Annotation> A getAnnotation(Class<A> annotationClass)

參數

  • annotationClass -- 對應於注釋類型的Class對象

返回值

此方法返回該元素的注解在此元素的指定注釋類型(如果存在),否則返回null

異常

  • NullPointerException -- 如果給定的注釋類是空的

  • IllegalMonitorStateException -- 如果當前線程不是這個對象監視器的所有者。

實例

下面的例子說明了如何使用lang.Object.getAnnotation()方法。

package com.yiibai;

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();
   }
}

讓我們來編譯和運行上面的程序,這將產生以下結果:

Demo Annotation 100


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM