注解(Annotation) by Thinking in Java

注解(元数据)为我们在代码中添加信息提供了一种形式化的方法,使我们可以在某个时刻非常方便的使用这些数据(受到了C#的启发 C#覆盖一个方法必须使用@Override,但是java不是必选的)

java SE5重要的语言的变化

  • 注解使得我们的能够以将有编译器来测试和验证的格式,存储有关程序的额外的信息
  • 注解可以用来生成描述符文件,甚至或是新的类定义,并有助于减轻编写样板代码的的负担
  • 使用注解,我们可以将这些元数据保存在Java代码中,并利用 annotion API 为自己的注解构造处理工具
  • 更加干净易读的代码以及编译器类型的检查
  • 虽然Java SE5提供一些元数据,但是一般来说,主要还是需要我们自己定义新的注解,并且按照自己的方法使用它们

定义注解

/**
 * author: Created by shiming on 2018/4/27 11:41
 * mailbox:lamshiming@sina.com
 *   @Target(ElementType.TYPE)   //接口、类、枚举、注解
 *   @Target(ElementType.FIELD) //字段、枚举的常量
 *   @Target(ElementType.METHOD) //方法
 *   @Target(ElementType.PARAMETER) //方法参数。参数声明
 *   @Target(ElementType.CONSTRUCTOR)  //构造函数,构造器的声明
 *   @Target(ElementType.LOCAL_VARIABLE)//局部变量
 *   @Target(ElementType.ANNOTATION_TYPE)//注解
 *   @Target(ElementType.PACKAGE) ///包
 */
@Target(ElementType.METHOD)//定义你的注解将应用在什么地方(一个方法,一个域)
@Retention(RetentionPolicy.RUNTIME)//定义注解在哪个级别可以使用,在源码中(SOURCE)、类文件中(CALSS),或者运行时(RUNTIME)
//没有元素的注解,称为标记注解(marker annotation),如果某个方法或者实现某个用例的需求,加上次方法,项目经理可以很好地观察到进度
//如果需要修改系统的业务逻辑,则维护改项目的开发人员也可以很容易的找到相对于的实例
public @interface Test {
}

关于RetentionPolicy 类

/**
 * author: Created by shiming on 2018/4/27 15:09
 * mailbox:lamshiming@sina.com
 */
public enum  RetentionPolicy {
        /**
         * Annotations are to be discarded by the compiler.
         * 注解将被编译器丢弃
         */
        SOURCE,

        /**
         * Annotations are to be recorded in the class file by the compiler
         * but need not be retained by the VM at run time.  This is the default
         * behavior.
         * 注解在class文件中可用,但会被VM丢弃
         */
        CLASS,

        /**
         * Annotations are to be recorded in the class file by the compiler and
         * retained by the VM at run time, so they may be read reflectively.
         * VM将在运行期也保留注解,因此可以通过反射机制读取注解的信息
         * @see java.lang.reflect.AnnotatedElement
         */
        RUNTIME

}

目前可以理解为注释


public class Testale {
    public void execute(){
        System.out.println("shiming execute");
    }
    @Test//就好比一个注释
    void testExecute(){
        execute();
    }
}

Demo----->

/**
 * author: Created by shiming on 2018/4/27 14:25
 * mailbox:lamshiming@sina.com
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCase {
    //由于编译器会对id进行类型检查,因此将用例文档的追踪数据库与源代码想关联是可靠的
    public int id();//默认值的限定,首先,元素不能有不确定的值,也就是说,元素必须要么具有默认值,要么具有使用元素提供的元素的值
    //如果注解某个方法没有给出值的话,则该注解的处理器就会使用此元素的默认值
    public String description() default "shiming no descriprition 我是默认的des";
}
/**
 * author: Created by shiming on 2018/4/27 14:35
 * mailbox:lamshiming@sina.com
 * 注解的元素在使用时候为名-值对的形式,并需要置于@USECase申明之后的括号内,在方法注解中可以给出description的值,也可以不给
 * 因此,在UseCase的注解处理器分析处理这个类时会使用该元素的默认值
 */
public class PasswordUtils {
    @UseCase(id = 1,description = "start need d  我是id==1")
    public boolean validatePassword(String s){
        return s.startsWith("d");
    }

    @UseCase(id = 2)
    public String validatePasswordReverse(String s){
        return new StringBuilder(s).reverse().toString();
    }

    @UseCase(id = 3,description = "start need 我是id==3")
    public boolean validatePasswordStirng(String s){
        return s.startsWith("shiming");
    }

}

如果没有用来读取注解的工具,那么注解也不会比注释更加有用

/**
 * author: Created by shiming on 2018/4/27 15:16
 * mailbox:lamshiming@sina.com
 *
 * 如果没有用来读取注解的工具,那么注解也不会比注释更加有用
 */
public class UseCaseTracker {
    @SuppressLint("UseValueOf")
    public static void trackUseCases(List<Integer> useCases, Class<?> cl){
        /**
         * getDeclaredMethods返回 Method 对象的一个数组,
         * 这些对象反映此 Class 对象表示的类或接口声明的所有方法,
         * 包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法
         */
        for (Method m:cl.getDeclaredMethods()){
            UseCase annotation = m.getAnnotation(UseCase.class);
            System.out.println("执行了第几次 "+annotation+"----->m.getName"+m.getName());
            if (annotation!=null){
                System.out.println("shiming  "+annotation.id()+"---->"+annotation.description());
                //注意这是元素还有角标的问题
                useCases.remove(new Integer(annotation.id()));
            }
            for (int i:useCases){
                System.out.println("shiming warning Missing usecase"+i);
            }
        }
    }
}

客户端调用

      ArrayList<Integer> integers = new ArrayList<>();
        integers.add(1);
        integers.add(2);
        integers.add(3);
        integers.add(4);
        UseCaseTracker.trackUseCases(integers,PasswordUtils.class);

执行结果如下

04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: 执行了第几次 null----->m.getNameaccess$super
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase1
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase2
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase3
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase4
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: 执行了第几次 @annotation.shimihg.demo.UseCase(description=start need d  我是id==1, id=1)----->m.getNamevalidatePassword
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming  1---->start need d  我是id==1
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase2
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase3
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase4
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: 执行了第几次 @annotation.shimihg.demo.UseCase(description=shiming no descriprition 我是默认的des, id=2)----->m.getNamevalidatePasswordReverse
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming  2---->shiming no descriprition 我是默认的des
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase3
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase4
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: 执行了第几次 @annotation.shimihg.demo.UseCase(description=start need 我是id==3, id=3)----->m.getNamevalidatePasswordStirng
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming  3---->start need 我是id==3
04-27 15:40:19.830 4425-4425/annotation.shimihg.com I/System.out: shiming warning Missing usecase4

未完待续,☺☺☺!git:https://github.com/Shimingli/AnnotationDemo

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,525评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,203评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,862评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,728评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,743评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,590评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,330评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,244评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,693评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,885评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,001评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,723评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,343评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,919评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,042评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,191评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,955评论 2 355

推荐阅读更多精彩内容

  • 本文章涉及代码已放到github上annotation-study 1.Annotation为何而来 What:A...
    zlcook阅读 29,161评论 15 116
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,657评论 18 139
  • 什么是注解(Annotation):Annotation(注解)就是Java提供了一种元程序中的元素关联任何信息和...
    九尾喵的薛定谔阅读 3,168评论 0 2
  • 第一次真正感受到聆聽的魅力,可以讓人如此心靜; 不帶任何立場的聆聽,可以讓我全身心感受到對方的需求; 最重要的是我...
    落子无悔ss阅读 122评论 0 0
  • 林放问礼之本。子曰:“大哉问!礼,与其奢也宁俭。丧,与其易也宁戚。” 林放问:“什么是礼的本原?”先生说:“你所问...
    一棵树2016阅读 658评论 0 1