java.lang.Package.isAnnotationPresent()方法實例
java.lang.Package.isAnnotationPresent(Class<? extends Annotation> annotationClass) 如果一個註解指定類型是存在於此元素上方法返回true,否則返回false。這種方法主要是爲了便於訪問標記註釋而設計。
聲明
以下是**java.lang.Package.isAnnotationPresent()**方法的聲明
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass)
參數
- annotationClass -- 對應於註釋類型的Class對象
返回值
如果一個註解指定註釋類型是存在於此元素上此方法返回true,否則返回false
異常
- NullPointerException -- 如果給定的註釋類爲null
例子
下面的例子顯示lang.Object.isAnnotationPresent()方法的使用。
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(); Package[] pack = Package.getPackages(); // check if annotation hello 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