注解在很多主流框架中都支持,自己编写代码的时候也会尽量用注解,一是方便,而是代码更加简洁。
注解的语法比较简单,除了@符的使用之外,它基本与Java固有语法一致。JavaSE5内置了三种标准注解:
@Override,表示当前的方法定义将覆盖超类中的方法。
@Deprecated,使用了注解为它的元素编译器将发出警告,因为注解@Deprecated是不赞成使用的代码,被弃用的代码。
@SuppressWarnings,提示编译器或工具软件禁止提示警告信息
上面的注解在写代码的时候多少会遇到。 Java还提供了4种注解,专门负责新注解的创建。
| 注解 | 属性功能 |
|---|---|
| @Target | 表示该注解可以用于什么地方,可能的ElementType参数有: CONSTRUCTOR:构造器的声明 FIELD:域声明(包括enum实例) LOCAL_VARIABLE:局部变量声明 METHOD:方法声明 PACKAGE:包声明 PARAMETER:参数声明 TYPE:类、接口(包括注解类型)或enum声明 |
| @Retention | 表示需要在什么级别保存该注解信息。可选的RetentionPolicy参数包括: SOURCE:注解将被编译器丢弃 CLASS:注解在class文件中可用,但会被VM丢弃 RUNTIME:VM将在运行期间保留注解,因此可以通过反射机制读取注解的信息 |
| @Document | 将注解包含在Javadoc中 |
| @Inherited | 允许子类继承父类中的注解 |
自定义注解:
它类似于新创建一个接口类文件,但为了区分,我们需要将它声明为@interface为自定义注释添加变量
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface AlexAnnotation {
public static enum FontColor { BLUE,RED,GREEN;};
String value();
String color() default "white";
int[] attr() default {1,2,3};
FontColor fontColor() default FontColor.BLUE;
}
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface UseCases {
public int value() default 0;
public int id() default 0;
public String description() default "no description";
}
使用注解:
@UserCase(id=10,description="my description")
注意:
注解元素必须有确定的值,要么在定义注解的默认值中指定,要么在使用注解时指定非基本类型的注解元素的值不可为null
注解快捷方式:如果注解元素声明为value(),则在使用注解时如果只声明value,可以只写值,不必写名值对,例如可写为@UserCase(10)
编写注解处理器
通过反射机制获取注解元素的值:Method.getAnnotation(),Field.getDeclaredAnnotations()等方法
SOURCE级别
@Override:保证方法能够正确重写,错误会提示。
由源码得到class文件,class里面不需要显示@Override,它的@Retention(RetentionPolicy.SOURCE)是SOURCE(编译)级别,目标是方法@Target(ElementType.METHOD),是注解在方法上面的。
package java.lang;
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.SOURCE)
public @interface Override {
}
CLASS级别
在java文件编译得到.class文件,在class文件里面任然还存在该注解
比如butterknife中的控件注解,就是CLASS级别。
@ViewInjector(R.id.text)在.class文件中还存在,在加载到虚拟机中就不存在了。只需要在编译时生成辅助类文件,在运行过程中不需要通过反射去读取注解的内容。
import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface ViewInjector{
int value();
}
RUNTIME级别
当.class文件加载到虚拟机的时候,该注解任然读取的到该注解。
import java.lang.annotation.ElementType;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ViewInjector{
int value();
}

被折叠的 条评论
为什么被折叠?



