ITPub博客

首页 > Linux操作系统 > Linux操作系统 > JAVA注解

JAVA注解

原创 Linux操作系统 作者:liiinuuux 时间:2012-11-13 17:49:39 0 删除 编辑
原创文章,转载请标明出处
http://space.itpub.net/26239116/viewspace-749136
创建注解
这里创建了OS和softWare两个注解,OS里有type,name和softWare的列表,
softWare里有软件的name和type
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface OS {
       public enum osType {linux, unix, aix};
       
       public osType type() default osType.linux;
       public String name();
       public Software[] softwares();
}

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Software {
       public enum sofwareType {SYSTEM, USER}
       public String name();
       public sofwareType type();
}


给函数添加注解
注解中应当以的
enum 类型变量相当于类中的public static 变量,可以直接引用
public class Computers {
       
       @OS(type = osType.linux, name = "red hat", softwares = {
                     @Software(name = "rpm", type = sofwareType.SYSTEM),
                     @Software(name = "oracle", type = sofwareType.USER) })
       public void computer1(){}
       
       @OS(type = osType.linux, name = "ubuntu", softwares = {
                     @Software(name = "wget", type = sofwareType.USER),
                     @Software(name = "firefox", type = sofwareType.USER) })
       public void computer2(){}
       
       @OS(type = osType.unix, name = "freeBSD", softwares = {
                     @Software(name = "ping", type = sofwareType.SYSTEM) })
       public void computer3(){}
}


在第三方获取注解
public class Main {
       public static void main(String[] args)
       {
              int softwareLen;
              for(Method method : Computers.class.getDeclaredMethods())
              {
                     OS os = (OS)method.getAnnotation(OS.class);
                     if(os == null)
                     {
                           continue;
                     }
                     softwareLen = os.softwares().length;
                     
                     System.out.println(os.type());
                     System.out.println(os.name());
                     if(softwareLen > 0)
                     {
                           for(Software software : os.softwares())
                           {
                                  System.out.println(software.name() + "  " + software.type());
                           }
                     }
              }
       }
}

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/26239116/viewspace-749139/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: IP包分片测试
请登录后发表评论 登录
全部评论

注册时间:2012-11-12

  • 博文量
    94
  • 访问量
    353432