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>
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>
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!