在运行时访问注释 [英] Access annotation at runtime

查看:34
本文介绍了在运行时访问注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在main中访问Sample类中的check是true还是false?
我应该在 Main 类中写什么?

How can I access in main whether check in the Sample class is true or false?
What should I write in Main class?

    package annotation;

    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;

    @Retention(RetentionPolicy.RUNTIME)

    public @interface annotation {
        public String name() default "Jimmy";
        public boolean check() default false;
    }

<小时>

    package annotation;

    @annotation(name = "Jack", check = false)

    public class Sample {

        public String str = "Hi";

        public void printHi(String str) {
            System.out.println(str);
        }
    }

<小时>

    package annotation;

    public class Main {
        public static void main(String[] args) {

        }
    }

推荐答案

使用 Sample.class.getAnnotation(annotation.class) 获取你的注解实例,并调用 check()获取校验值:

System.out.println(Sample.class.getAnnotation(annotation.class).check());

请注意,类应该以大写字母开头,并且将注释命名为annotation"很容易混淆.

Note that classes should start with an upper-case letter, and that naming an annotation "annotation" is quite confusing.

这篇关于在运行时访问注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆