免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 861 | 回复: 0
打印 上一主题 下一主题

自定义annotaion的实例 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-12-22 08:51 |只看该作者 |倒序浏览

package com.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;s
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Description {
 String value();
}

--------------------------------------------------------------------------------------

package com.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)
@Documented
public @interface Mess {
 
 String name();

 String book();

}


--------------------------------------------------------------------------------------

package com.annotation;

@Description("javaeye,做最棒的软件开发交流社区")
public class JavaBook {

 @Mess(name = ("姓名:西门吹雪"), book = ("著作:java编程细想"))
 public String getName() {
  return "java编程思想讲述了很多设计思想";
 }
 @Mess(name = "姓名:叶孤城", book = "著作:关于OGNL的研究")
 public String getName2() {
  return "OGNL是对象图形导航的语言";
 }

}

class com.annotation.TestAnnotation
--------------------------------------------------------------------------------------

package com.annotation;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

public class TestAnnotation {
 /** 
     *  Annotation的使用实例
     */ 
       public static void main(String[] args) throws Exception {  
       String  CLASS_NAME = "com.annotation.JavaBook";  
       Class  test = Class.forName(CLASS_NAME);  
       Method[] method = test.getMethods();  
       boolean flag = test.isAnnotationPresent(Description.class);  
        if(flag)  
        {  
            Description des = (Description)test.getAnnotation(Description.class);  
            System.out.println("描述:"+des.value());  
        }  
          
        //把JavaBook这一类有利用到@Mess的全部方法保存到Set中去  
        Set<Method> set = new HashSet<Method>();  
        for(int i=0;i<method.length;i++)  
        {  
            boolean otherFlag = method[i].isAnnotationPresent(Mess.class);  
            if(otherFlag) set.add(method[i]); 
        }  
        for(Method m: set)  
        {  
         Mess name = m.getAnnotation(Mess.class);  
            System.out.println(name.name());  
            System.out.println(name.book());  
        }  
     }  

}

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP