Home > Java > javaTutorial > How to Access Annotation Values at Runtime in Java?

How to Access Annotation Values at Runtime in Java?

Susan Sarandon
Release: 2024-10-26 05:59:30
Original
1027 people have browsed it

How to Access Annotation Values at Runtime in Java?

Accessing Annotation Values in Java

Java annotations provide a mechanism for adding metadata to code elements, such as classes, methods, and fields. By default, annotations are only available during compilation and are discarded at runtime. However, by specifying the RetentionPolicy.RUNTIME value in the Retention annotation, you can preserve annotations at runtime.

Access Annotation Values from Another Class

If an annotation has the RetentionPolicy.RUNTIME retention policy, you can use Java reflection to read its value from another class. Here's how:

<code class="java">// Import the necessary classes
import java.lang.reflect.Field;
import java.lang.annotation.Annotation;

// Get the class object
Class<?> clazz = MyClass.class;

// Iterate over the fields of the class
for (Field field : clazz.getFields()) {

    // Check if the field has the Column annotation
    Annotation annotation = field.getAnnotation(Column.class);

    // If the annotation exists, read its columnName() value
    if (annotation != null) {
        String columnName = ((Column) annotation).columnName();
        System.out.println("Column Name: " + columnName);
    }
}</code>
Copy after login

Accessing Private Fields

The getFields() method only retrieves public fields. To access private fields, use getDeclaredFields() instead:

<code class="java">for (Field field : clazz.getDeclaredFields()) {

    ...
}</code>
Copy after login

The above is the detailed content of How to Access Annotation Values at Runtime in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template