Java自定义注解Annotation
定义注解:
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)@Documentedpublic @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"); } } }}