溫馨提示×

java怎么獲取注解的值

小億
223
2023-11-09 11:54:32
欄目: 編程語言

在Java中,要獲取注解的值,可以使用反射機制。
以下是一個示例代碼,演示如何獲取注解的值:

// 定義一個注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface MyAnnotation {

????String?value(); } //?使用注解 @MyAnnotation(“Hello”) class?MyClass?{

???? } public?class?Main?{

????public?static?void?main(String[]?args)?{

????????//?獲取注解的值

????????MyAnnotation?annotation?=?MyClass.class.getAnnotation(MyAnnotation.class);

????????if?(annotation?!=?null)?{

????????????String?value?=?annotation.value();

????????????System.out.println(value);??//?輸出:Hello

????????}

????} }

在上述代碼中,首先定義了一個注解MyAnnotation,該注解有一個屬性value。
然后在MyClass類上使用了MyAnnotation注解,同時指定了注解的值為Hello。
Main類中,通過MyClass.class.getAnnotation(MyAnnotation.class)方法獲取MyClass類上的MyAnnotation注解的值,然后可以通過annotation.value()方法獲取注解的值,并進行相應的操作。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女