Java.lang.Package.getAnnotations() 方法

描述

java.lang.Package.getAnnotations() 方法返回此元素上存在的所有注释。 (如果此元素没有注释,则返回长度为零的数组。)此方法的调用者可以自由修改返回的数组; 它不会影响返回给其他调用者的数组。


声明

以下是 java.lang.Package.getAnnotations() 方法的声明。

public Annotation[] getAnnotations()

参数

NA


返回值

此方法返回此元素上存在的所有注释


异常

NA


示例

下面的例子展示了 lang.Object.getAnnotations() 方法的使用。

package com.tutorialspoint;

import java.lang.annotation.Annotation;
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 annotations
         Annotation[] annotation = m.getAnnotations();

         // print the annotation
         for (int i = 0; i < annotation.length; i++) {
            System.out.println(annotation[i]);
         }
      } catch (NoSuchMethodException exc) {
         exc.printStackTrace();
      }
   }
   public static void main(String args[]) {
      example();
   }
}

让我们编译并运行上面的程序,这将产生下面的结果 −

@com.tutorialspoint.Demo(str=Demo Annotation, val=100)