Java 注解总结

Java 注解总结

注解的作用

注解是是一类用于描述代码信息的的原数据,注解本身并非其注释的代码的一部分。它主要的作用在于:

  • 向编译器提供信息以检查编译错误
  • 提供编译&部署期间处理时所需要信息,编译/部署软件可以通过处理注解生成代码,XML文件等
  • 提供运行时信息,部分注解可以保留到运行时形成部分代码逻辑

JDK中的常用注解

JDK中内置的常用注解有如下几类:

  • @Override
  • @SuppressWarnings
  • @Deprecated

使用方法分别如下:

@Override

@Override 用于标记一个方法重写了父类的一个方法,如果一个方法添加了@Override注解,编译器会检查该方法父类是否存在可以被重写的同名方法,如果没有则提示编译错误,例如:

package com.annotation.test;

public class TestAnnotation {

    public static void main(String[] args) {
        Human woman = new Woman();
        woman.dressSomething();
    }

    static class Human {
        protected void dressSomething() {
            System.out.println("Human dress chloth");
        }
    }

    static class Woman extends Human {

        public void dresssomething() {
            System.out.println("Woman dress skirt ");
        }
    }
}

编译Woman类是不小心将some达成了小写,因此成语错误的输出了:

Human dress chloth

如果在为Woman类dressomething方法增加@Override注解:

static class Woman extends Human {
    @Override
    public void dresssomething() {
        System.out.println("Woman dress skirt ");
    }
}

那么在编译器期间就会提示如下错误,从而避免在运行时出错:

The method dressomething() of type TestAnnotation.Woman must override or implement a supertype method

@Deprecated

@Depreacated注解用于声明方法,成员,构造函数等内容已经被废弃,编译器如果发现代码使用了被@Deprecated注解的内容会在编译期间提出警告。例如如下代码:

public class TestAnnotation {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
            }
        });
        thread.start();
        thread.destroy();
    }
}

编译时提示如下警告:

javac TestAnnotation.java
注: TestAnnotation.java使用或覆盖了已过时的 API。
注: 有关详细信息, 请使用 -Xlint:deprecation 重新编译。

@SupressWarning

@SupressWarning可以用于注解类,方法,参数,构造函数等内容。被@SupressWarning注解的内容在编译期间不会提示警告,录入在前一个例子中的main方法增加,编译结果无任何警告。

@SuppressWarnings("deprecation")
public static void main(String[] args) {
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
        }
    });
    thread.start();

    thread.destroy();
}

自定义注解

自定义注解的语法非常简单,如下:

@interface AnootationName{}

元注解

在学习自定义注解之前首先来了解几个用于修饰自定义注解的注解,这几个注解用于标注注解的基本行为。

@Target

@Target 用于标注所定义的注解可以作用于哪些内容,他的取值可以是java.lang.annotation.ElementType中的一种,具体如下:

枚举值 作用域
TYPE class,interface,enum
FIELD fields
METHOD method
CONSTRUCTOR constructors
LOCAL_VARIABLE local variables
ANNOTATION_TYPE annotation
PARAMETER parameter

@Retention

@Retention 用于说明注解可以保留到哪些阶段,起取值和含义如下:

作用
RetentionPolicy.SOURCE 在编译期间被丢掉,在class文件中不存在
RetentionPolicy.CLASS 会编译到class文件中,编译器可以读取,但是运行时无法读取到
RetentionPolicy.RUNTIME 会表一到class文件中,运行时也可以通过反射读取

@Inherited

@Inherited 用于标注一个注解可以被子类继承,例如:

@Inherited 
@interface MyAnnotation{}

@MyAnnotation
class superclas {
}

class Subclass extends Superclass{}  

Subclass也被@MyAnnotation标注。

自定义注解语法

标记注解

标记注解中没有任何Field,定义和使用方法如下:

@interface MyAnnotation{}

@MyAnnotation
class superclas {
}

单值注解

单值注解是指,注解中进含有一个Field,定义及使用方法如下:

@Target(ElementType.METHOD)
@interface SingleValueAnnotation{
    String description() default "default"; 
}

@SingleValueAnnotation
String  getDescription() {
    return "null";
}

@SingleValueAnnotation(description = "WOW")
String getDescptionAlt() {
    return "invalid";
}

多值注解

多至注解是指,注解中包含一個以上的Field,定义和使用如下:

@Target(ElementType.METHOD)
@interface MultiValueAnnotation {
    String description() default "dafault";
    int seed();
    Class<?> myClass();
}

@MultiValueAnnotation(seed = 0, myClass = TestAnnotation.class)
void printValues() {

}

多值注解和单值注解有下面几个地方需要注意:

  1. 自定义注解中的Field的类型只能是,原始类型,String,枚举,class,注解
  2. 自定义注解中的Field的默认值可以通过 default 关键字制定
  3. 使用自定义注解时,必须对没有默认值的Field赋值

示例

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public class TestAnnotation {

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @interface MarkerAnnotation {
    }

    @Target(ElementType.CONSTRUCTOR)
    @interface OneValueAnnotation {
        String descrpiton() default "Hellow World";
    }

    @Target({
            ElementType.METHOD, ElementType.FIELD
    })
    @Retention(RetentionPolicy.RUNTIME)
    @interface MultiValuieAnnotation {
        String description();

        int seed() default 2018;
    }

    @MarkerAnnotation
    static class Human {
        @MultiValuieAnnotation(description = "mName", seed = 2017)
        String mName;

        @OneValueAnnotation
        public Human() {
            mName = "human";
        }

        @MultiValuieAnnotation(description = "eat")
        public void eat() {
            System.out.println("Humant eat");
        }
    }

    static class Woman extends Human {
        @Override
        public void eat() {
            System.out.println("Woman eat");
        }
    }

    public static void main(String[] args) {

        MarkerAnnotation humanMarkerAnnotation = Human.class.getAnnotation(MarkerAnnotation.class);
        System.out.println("humanMarkerAnnotation: " + humanMarkerAnnotation);

        MarkerAnnotation womanMarkerAnnotation = Woman.class.getAnnotation(MarkerAnnotation.class);
        System.out.println("womanMarkerAnnotation:" + womanMarkerAnnotation);

        try {
            OneValueAnnotation humanConstructorAnnotation = Human.class.getConstructor()
                    .getAnnotation(OneValueAnnotation.class);
            System.out
                    .println("humanConstructorAnnotation:" + humanConstructorAnnotation);

            MultiValuieAnnotation humanFieldAnnotation = Human.class.getDeclaredField("mName")
                    .getAnnotation(MultiValuieAnnotation.class);
            System.out.println("humanFieldAnnotation:" + humanFieldAnnotation);

            MultiValuieAnnotation humantMethodAnnotation = Human.class.getMethod("eat")
                    .getAnnotation(MultiValuieAnnotation.class);
            System.out.println("humantMethodAnnotation:" + humantMethodAnnotation);
        } catch (NoSuchMethodException | SecurityException | NoSuchFieldException e) {
            e.printStackTrace();
        }
    }
}

输出结果如下:

humanMarkerAnnotation: @com.annotation.test.TestAnnotation$MarkerAnnotation()
womanMarkerAnnotation:@com.annotation.test.TestAnnotation$MarkerAnnotation()
humanConstructorAnnotation:null
humanFieldAnnotation:@com.annotation.test.TestAnnotation$MultiValuieAnnotation(seed=2017, description=mName)
humantMethodAnnotation:@com.annotation.test.TestAnnotation$MultiValuieAnnotation(seed=2018, description=eat)

总结:

  1. @Retention 为RUNTIME的注解可以在运行时通过反射读取
  2. 注解没有Modifier,主要获取到了Field,class,constructor等内容,即可读取注解

实际应用AndroidEventHub

To Be Continue...

参考文档

Java Annotation
Java Custom Annotation

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

推荐阅读更多精彩内容