读书人

Java自定义注脚Annotation

发布时间: 2012-10-29 10:03:53 作者: rapoo

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");            }        }    }}


运行输出结果:

hasAnnotation ?
yes

读书人网 >编程

热点推荐