import java.lang.annotation.*;
import java.lang.reflect.*;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str();
int val();
}
@Retention(RetentionPolicy.RUNTIME)
@interface OtherAnno {
String str();
}
class Test {
@MyAnno(str="foo annotation", val=100)
public void foo() {
System.out.println("bar");
}
@MyAnno(str="bar annotation", val=200)
public void bar(int a, int b) {
System.out.println(a + b);
}
@OtherAnno(str="baz annotation")
@MyAnno(str="baz annotation 2", val=300)
public void baz(String s) {
System.out.printf("[%s]\n", s);
}
}
class Main {
public static void main(String[] args) throws NoSuchMethodException {
Class<?> c = Test.class;
Method m1 = c.getMethod("foo");
MyAnno anno1 = m1.getAnnotation(MyAnno.class);
System.out.println(anno1.str() + " " + anno1.val());
Method m2 = c.getMethod("bar", int.class, int.class);
MyAnno anno2 = m2.getAnnotation(MyAnno.class);
System.out.println(anno2.str() + " " + anno2.val());
Method m3 = c.getMethod("baz", String.class);
Annotation[] annos = m3.getAnnotations();
for (Annotation a: annos) {
System.out.println(a);
}
System.out.println(m2.isAnnotationPresent(OtherAnno.class));
System.out.println(m3.isAnnotationPresent(OtherAnno.class));
}
}
To embed this program on your website, copy the following code and paste it into your website's HTML: