测试代码
@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface MyAnnotation {
String value() default "unknown"; //这是个什么写法?
}
public class TestMyAnnotation {
@MyAnnotation(value = "ss")
public String getString(Integer i,String s){
//此处必须是public否则出现NoSuchMethodException
System.out.println(i.toString()+s);
return s;
}
public static void main(String[] args) {
Class<TestMyAnnotation> c = TestMyAnnotation.class;
TestMyAnnotation t = new TestMyAnnotation();
Method method = null;
try {
method = c.getMethod("getString", new Class[]{Integer.class, String.class});
method.invoke(t,new Object[]{18,"sss"});
if(method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println(annotation);
System.out.println(annotation.value());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}