Language
annotation: RUNTIME保持ならreflectionから読める
RetentionPolicy.RUNTIMEを指定したannotationだけが、実行時のreflection APIで取得できます。
SourceRuntimeLabels.java
Java 21
package examples.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public final class RuntimeLabels {
private RuntimeLabels() {}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Label {
String value();
}
@Label("billing")
public static final class BillingService {}
}TestRuntimeLabelsTest.java
Java 21
package examples.annotation;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class RuntimeLabelsTest {
@Test
void RUNTIME保持のannotationはreflectionから取得できる() {
var label = RuntimeLabels.BillingService.class.getAnnotation(RuntimeLabels.Label.class);
assertEquals("billing", label.value());
}
}01Assertion
このテストで確認できること
- 型へRUNTIME保持のannotationを付与する
- getAnnotationで値を取得できる
フレームワークやライブラリが実行時にannotationを読むにはRUNTIME保持が必要です。保持ポリシーは単なるメタ情報ではなく公開契約です。
OBSERVED RESULT
expected: label → billing
actual: billing