HFDev
HFDev

Reputation: 141

Access annotation at runtime

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

        }
    }

Upvotes: 3

Views: 966

Answers (1)

JB Nizet
JB Nizet

Reputation: 692161

Use Sample.class.getAnnotation(annotation.class) to get your annotation instance, and call check() to get the check value:

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

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

Upvotes: 7

Related Questions