首頁  >  文章  >  Java  >  如何在 Java 運行時存取註解值?

如何在 Java 運行時存取註解值?

Susan Sarandon
Susan Sarandon原創
2024-10-26 05:59:30950瀏覽

How to Access Annotation Values at Runtime in Java?

存取Java 中的註解值

Java 註解提供了一種將元資料新增至程式碼元素(例如類別、方法和字段)的機制。預設情況下,註釋僅在編譯期間可用,並在運行時被丟棄。但是,透過在 Retention 註解中指定 RetentionPolicy.RUNTIME 值,您可以在執行時間保留註解。

從另一個類別存取註解值

如果註解具有RetentionPolicy.RUNTIME保留策略,可以使用Java反射從另一個類別讀取其值。方法如下:

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

存取私有欄位

getFields() 方法只擷取公用欄位。若要存取私有字段,請使用 getDeclaredFields() 取代:

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

    ...
}</code>

以上是如何在 Java 運行時存取註解值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn