java.lang.Package.getAnnotation(Class<A> annotationClass) 方法返回這個元素的註解指定類型,若是這樣的註釋,不然返回null。java
如下是java.lang.Package.getAnnotation()方法的聲明yii
public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
annotationClass -- 對應於註釋類型的Class對象ide
此方法返回這個元素的註解指定註釋類型,若是存在於此元素上,不然返回nullspa
NullPointerException -- 若是給定的註釋類爲null線程
IllegalMonitorStateException -- 若是當前線程不是對象監視器的擁有者。orm
下面的例子顯示了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(); }}
讓咱們來編譯和運行上面的程序,這將產生如下結果:get
Demo Annotation 100