java 注解

来源:互联网 发布:ubuntu 查看命令参数 编辑:程序博客网 时间:2024/06/05 01:55

【java开发系列】—— 自定义注解


http://www.cnblogs.com/xing901022/p/3966799.html


其他的不多说了,标准元注解 都是干嘛的呢?

  @Documented 标记生成javadoc

  @Inherited 标记继承关系

  @Retention 注解的生存期

  @Target 标注的目标

  

下面我们自己做一个注解!

  首先声明一个接口,并未它添加注解内容!

复制代码
 1 package testAnnotation; 2  3 import java.lang.annotation.Documented; 4 import java.lang.annotation.Retention; 5 import java.lang.annotation.RetentionPolicy; 6  7 @Documented 8 @Retention(RetentionPolicy.RUNTIME) 9 public @interface Person{10     String name();11     int age();12 }
复制代码

  一般来说,注解都是搭配反射的解析器共同工作的。然后利用反射机制查看类的注解内容

复制代码
 1 package testAnnotation; 2  3 @Person(name="xingoo",age=25) 4 public class test3 { 5     public static void print(Class c){ 6         System.out.println(c.getName()); 7          8         //java.lang.Class的getAnnotation方法,如果有注解,则返回注解。否则返回null 9         Person person = (Person)c.getAnnotation(Person.class);10         11         if(person != null){12             System.out.println("name:"+person.name()+" age:"+person.age());13         }else{14             System.out.println("person unknown!");15         }16     }17     public static void main(String[] args){18         test3.print(test3.class);19     }20 }
复制代码

  运行结果,读取到了注解的内容

testAnnotation.test3name:xingoo age:25

0 0
原创粉丝点击