15207

Question:
How can I access in main
whether check
in the Sample
class is true or false?<br />
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;
}
<hr /> package annotation;
@annotation(name = "Jack", check = false)
public class Sample {
public String str = "Hi";
public void printHi(String str) {
System.out.println(str);
}
}
<hr /> package annotation;
public class Main {
public static void main(String[] args) {
}
}
Answer1:Use <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getAnnotation%28java.lang.Class%29" rel="nofollow">Sample.class.getAnnotation(annotation.class)
</a> 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.