SoFunction
Updated on 2025-03-08

Package details

Package is a core package in the Java standard library, specifically used to define and support Java annotations. This package contains some core interfaces and enumeration types to define and control how annotations behave and used in Java programs.

Main classes and interfaces

Annotation interface

Parent interface for all annotation types. All custom annotation types implicitly implement this interface. Through this interface, the annotation metadata information can be obtained.

ElementType Enumeration

Defines the type of program element that can be applied to the annotations. include:TYPEFIELDMETHODPARAMETERCONSTRUCTORLOCAL_VARIABLEANNOTATION_TYPEPACKAGE. These constants determine which parts annotations can be used to annotate.

RetentionPolicy Enumeration

Defines the retention strategy for annotations. include:SOURCECLASSRUNTIME. These constants determine when annotations are visible, i.e. when compile, run, or only in the source code.

Meta Note

Meta-annotations are comments specifically used to annotate other comments, located inThe main meta annotations in the package are:

@Retention

Control the retention strategy of annotations and determine the life cycle of annotations.

@Target

Specifies the type of program element that annotations can apply.

@Documented

Indicates whether the annotation is included in the Javadoc.

@Inherited

Indicates whether annotations can be inherited by subclasses. Example of usage

Here is a simple example showing how to define and use custom annotations and get annotation information through reflection:

import .*;
import ;
// Custom annotations@Retention()
@Target()
@interface MyAnnotation {
    String value();
}
// Use custom annotationspublic class MyClass {
    @MyAnnotation(value = "Example")
    public void myMethod() {
        ("Hello, world!");
    }
}
// Read annotation informationpublic class AnnotationTest {
    public static void main(String[] args) {
        try {
            Method method = ("myMethod");
            if (()) {
                MyAnnotation annotation = ();
                ("Annotation value: " + ());
            }
        } catch (NoSuchMethodException e) {
            ();
        }
    }
}

In this example,MyAnnotationIt is a custom annotation, used@Retention()and@Target()Meta-annotations to define its behavior and scope of application. existMyClassIn the classmyMethodApplied on the methodMyAnnotationAnnotation, and inAnnotationTestThe annotation information is read through reflection in the class.

This is all about this article about package introduction. For more related package content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!