定义注解:
注解的使用:
测试:
运行输出结果:
hasAnnotation ?
yes
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
}
注解的使用:
public class AnnotationDemo {
@MyAnnotation
public void hasAnnotation() {
System.out.println("hasAnnotation ?");
}
}
测试:
public class AnnotationDemoTest {
@Test
public void test() {
Method[] methods = AnnotationDemo.class.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyAnnotation.class)) {
try {
method.invoke(new AnnotationDemo(), new Object[] {});
}
catch (IllegalArgumentException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
catch (InvocationTargetException e) {
e.printStackTrace();
}
System.out.println(" yes");
}
}
}
}
运行输出结果:
hasAnnotation ?
yes