Course contentsShow
← Java
Lesson 2450 of 2,87046. AnnotationsFree lesson

ElementType.PACKAGE and MODULE

Use PACKAGE for package-info.java annotations and MODULE for module declarations.

ElementType.PACKAGE and MODULE

What you'll learn: How to use ElementType.PACKAGE and ElementType.MODULE to annotate package and module declarations in Java.


Where Annotations Go Beyond Classes and Methods

You've seen annotations on classes, methods, fields, and even local variables. But Java programs have two additional organizational levels: packages and modules. These can be annotated too, using special ElementType values.

ElementType.PACKAGE: Annotating Packages

The PACKAGE target allows annotations on package declarations. These annotations go in a special file called package-info.java within the package directory.

Structure:

// In src/com/example/myapp/package-info.java

@Deprecated(since = "2.0", forRemoval = true)
package com.example.myapp;

Think of package-info.java as the package's "about me" page—it documents and configures the entire package. You might use PACKAGE-targeted annotations for:

  • Deprecating entire packages
  • Marking packages as nullable or non-null by default
  • Documenting package-level contracts or configurations

Declaring a PACKAGE annotation:

@Target(ElementType.PACKAGE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PackageVersion {
    String value();
}

ElementType.MODULE: Annotating Module Declarations

Introduced in Java 9, MODULE targets annotations on module declarations in module-info.java.

Structure:

// In module-info.java

@ModuleVersion("1.5.0")
module com.example.myapp {
    exports com.example.myapp.api;
}

This lets frameworks or tools process module-level metadata—versioning, security policies, or configuration.

Declaring a MODULE annotation:

@Target(ElementType.MODULE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ModuleVersion {
    String value();
}

Key Takeaway: Use @Target(ElementType.PACKAGE) for annotations in package-info.java to configure entire packages, and @Target(ElementType.MODULE) in module-info.java to annotate module declarations—both enable organizational-level metadata.