ZBLOG

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface MyAnnotation { String value() default ""; } public class Test { @MyAnnotation(value = "example") private String myField;}

根据你提供的代码,MyAnnotation 是一个自定义的注解,它具有 @Retention(RetentionPolicy.RUNTIME)@Target(ElementType.FIELD) 注解。这表示该注解在运行时可用,并且可以应用于类的字段上。

而在 Test 类中,使用了 @MyAnnotation(value = "example") 将注解应用于 myField 字段上。

这样,通过反射机制可以获取到字段上的注解,并访问其中定义的值。例如:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MyAnnotation {
    String value() default "";
}

public class Test {
    @MyAnnotation(value = "example")
    private String myField;

    public static void main(String[] args) throws NoSuchFieldException {
        Field field = Test.class.getDeclaredField("myField");
        MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
        System.out.println(annotation.value()); // 输出:example
    }
}

以上代码会输出 "example",表示成功获取到了字段上注解中定义的值。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=10892

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?