首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Java自定义注脚Annotation

2012-10-29 
Java自定义注解Annotation定义注解:import java.lang.annotation.Documentedimport java.lang.annotation

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

热点排行