Java Package isAnnotationPresent()方法

java.lang.Package.isAnnotationPresent(Class<? extends Annotation> annotationClass) 如果一个注解指定类型是存在于此元素上方法返回true,否则返回false。这种方法主要是为了便于访问标记注释而设计。

1 语法

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

2 参数

annotationClass :对应于注释类型的Class对象

3 返回值

如果一个注解指定注释类型是存在于此元素上此方法返回true,否则返回false

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Enum compareTo()方法
 */
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

 

热门文章

优秀文章