在Android开发中咱们常常会用到注解,例如@Override
Butterknife中的BindView
等。这里主要记录下注解怎么写和简单的使用。html
咱们经过Override
注解的定义来切入注解的语法。java
@Target(ElementType.METHOD) @Retention(RetentionPolicy.SOURCE) public @interface Override { }
在java源码中,经过上面的几行代码就定义了一个Override
的注解,定义注解的时候用到了两个元注解Target
,Retention
。什么是元注解?注解注解的注解就是元注解。跟定义接口差很少,就是用到的是@interface
,而后加上了元注解。那么元注解的做用是什么呢?android
元注解:@Target
,@Retention
,@Documented
,@Inherited
数组
@Target说明了注解所修饰对象的类型。由EelmentType
所描述编辑器
public enum ElementType { TYPE, //class interface enum FIELD, //域 METHOD, //方法 PARAMETER, //参数 CONSTRUCTOR, //构造 LOCAL_VARIABLE, //局部变量 ANNOTATION_TYPE, //注解 PACKAGE, //包 }
实例:ide
/** * 这样咱们就定义了一个做用在类型和域上面的注解 */ @Target({ElementType.TYPE, ElementType.FIELD}) public @interface Entity { }
@Retention
代表注解做用的时间。由RetentionPolicy
所描述工具
public enum RetentionPolicy { /** * 只在源码显示,编译时丢弃; */ SOURCE, /** * 编译时记录到.class中,运行时忽略;默认值 */ CLASS, /** * 运行时保留,运行中能够处理。(咱们用的较多的就是这个) */ RUNTIME }
含有该注解类型的元素(带有注释的)会经过javadoc或相似工具进行文档化。
咱们来对比一下:性能
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface NoDocumented { } @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TestDocumented { } @TestDocumented public void funTestDocumented(){ System.out.println("有@Documented"); } @NoDocumented public void funNoDocucmented(){ System.out.println("无@Documented"); }
定义以上两个注解并测试,利用javadoc生成文档后显示以下:测试
根据字面意思是继承。也就是标识该注解能够被继承。只做用在类上面。spa
@Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Entity { String value() default ""; int name() default 0; }
咱们在定义注解的时候,能够添加相关的参数。定义了参数以后咱们就能够经过反射的方式获取到注解,而后获取该参数了。以下所示:
Class<TestInheritedC> cClass = TestInheritedC.class; Entity annotation = cClass.getAnnotation(Entity.class); if (annotation != null) { String value = annotation.value(); int name = annotation.name(); System.out.println("value = " + value + " name = " + name); }
注解参数的类型包括:基本数据类型
,String
,Class
,Enum
,Annotation
,及前边这些类型的数组类型
。
@Override 重写了父类的方法
@Deprecated 表示已过期,不推荐使用。通常在使用被标注的方法、类等时编辑器会出现删除线。
@@SuppressWarnnings 用于通知Java编译器关闭对特定类、方法、成员变量、变量初始化的警告
compile 'com.android.support:support-annotations:24.2.0'
support-annotations
包为咱们提供了不少实用的注解,来方便代码的检查,例如 @Nullable
,@NonNull
等,具体的使用参考Android官方文档。
这里说一下类型的定义IntDef
和StringDef
,在开发中常常要使用Enum
类型。不过Enum
在开发中性能不如常量。咱们能够使用注解的方式进行替换。例以下面是View
源码中的一个栗子
@IntDef({VISIBLE, INVISIBLE, GONE}) @Retention(RetentionPolicy.SOURCE) public @interface Visibility {}
借用官方文档上的栗子,是这么使用的:
// Define the list of accepted constants and declare the NavigationMode annotation @Retention(RetentionPolicy.SOURCE) @IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST, NAVIGATION_MODE_TABS}) public @interface NavigationMode {} // Declare the constants public static final int NAVIGATION_MODE_STANDARD = 0; public static final int NAVIGATION_MODE_LIST = 1; public static final int NAVIGATION_MODE_TABS = 2; // Decorate the target methods with the annotation @NavigationMode public abstract int getNavigationMode();