Java - Add & Get Package Level AnnotationsThis tutorial shows you how to add a package level annotation and how to get the annotations of a package.

Java allows you to add annotations. They can be added in different places such as method, type (e.g. class, interface), parameter, variable, and package. In this tutorial, we are going to focus on package level annotation.

Create the Annotation

If you want to add an annotation to a package, you have to make sure that the annotation can be used on package level. An annotation declaration may have a @Target meta-annotation. It's used by the compiler to enforce the usage restrictions. If the array passed to the @Target meta-annotation contains PACKAGE, it means the annotation can be used on package level. If there's a @Target meta-annotation but the array doesn't include PACKAGE, you cannot use the annotation on package level.

Below is an example of an annotation that can be used on package level.

  @Target({PACKAGE, TYPE})
  @Retention(RUNTIME)
  public @interface MyAnnotation {

    String name();
  }

If the @Target meta-annotation is not present, there are no restrictions and the annotation can be used as a modifier for any declaration.

 

So, if you use an existing annotation, you may need to check the value of the @Target meta-annotation. If you create your own annotation, make sure that you allow it to be used on package level.

Add the Annotation to a Package

Annotating a package with an annotation is a bit different from adding it at another location such as a class, a method, or a variable. Usually, the annotation can be directly in the same file. In Java, a package is declared by using a directory path in Java. To add additional information to the package, you need to put a file named package-info.java. The file must be put in the directory of the package.

Inside the package-info.java file, you need to write the package name, just like in other .java files. Then, you can add some annotations above the package name.

  @MyAnnotation(name = "Woolha.com")
  package com.woolha.example;

Get Annotations of a Package

To get the annotations of a package, first you need a reference to the package object. It can be done by calling the getPackage() method of any class. Having got the package object, whose type is Package, you can call the getAnnotations() method which returns an array of annotations that the package has. Then, you can iterate over the array to get the list of annotation names.

    Package myPackage = MyClass.class.getPackage();
    Annotation[] annotations = myPackage.getAnnotations();

    for (Annotation annotation : annotations) {
      System.out.println(annotation.annotationType());
    }

Summary

In this tutorial, we have learned how to add and get package level annotations. They have to be added in a package-info.java file. Then, you can get the list of annotation names by calling the getAnnotations() method of a Package object.