一、什么是注解
注解可以向編譯器、虛擬機等解釋說明一些事情。舉一個最常見的例子,當我們在子類當中覆寫父類的aMethod方法時,在子類的aMethod上會用@Override來修飾它,反之,如果我們給子類的bMethod用@Override注解修飾,但是在它的父類當中并沒有這個bMethod,那么就會報錯。這個@Override就是一種注解,它的作用是告訴編譯器它所注解的方法是重寫父類的方法,這樣編譯器就會去檢查父類是否存在這個方法。
注解是用來描述Java代碼的,它既能被編譯器解析,也能在運行時被解析。
二、元注解
元注解是描述注解的注解,也是我們編寫自定義注解的基礎,比如以下代碼中我們使用@Target元注解來說明MethodInfo這個注解只能應用于對方法進行注解:
@Target(ElementType.METHOD)
public @interface MethodInfo {
//....
}
下面我們來介紹4種元注解,我們可以發(fā)現這四個元注解的定義又借助到了其它的元注解:
2.1 Documented
當一個注解類型被@Documented元注解所描述時,那么無論在哪里使用這個注解,都會被Javadoc工具文檔化,我們來看以下它的定義:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
//....
}
- 定義注解時使用
@interface關鍵字: -
@Document表示它本身也會被文檔化; -
Retention表示@Documented這個注解能保留到運行時; -
@ElementType.ANNOTATION_TYPE表示@Documented這個注解只能夠被用來描述注解類型。
2.2 Inherited
表明被修飾的注解類型是自動繼承的,若一個注解被Inherited元注解修飾,則當用戶在一個類聲明中查詢該注解類型時,若發(fā)現這個類聲明不包含這個注解類型,則會自動在這個類的父類中查詢相應的注解類型。
我們需要注意的是,用inherited修飾的注解,它的這種自動繼承功能,只能對類生效,對方法是不生效的。也就是說,如果父類有一個aMethod方法,并且該方法被注解a修飾,那么無論這個注解a是否被Inherited修飾,只要我們在子類中覆寫了aMethod,子類的aMethod都不會繼承父類aMethod的注解,反之,如果我們沒有在子類中覆寫aMethod,那么通過子類我們依然可以獲得注解a。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
//....
}
2.3 Retention
這個注解表示一個注解類型會被保留到什么時候,它的原型為:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
其中,RetentionPolicy.xxx的取值有:
-
SOURCE:表示在編譯時這個注解會被移除,不會包含在編譯后產生的class文件中。 -
CLASS:表示這個注解會被包含在class文件中,但在運行時會被移除。 -
RUNTIME:表示這個注解會被保留到運行時,我們可以在運行時通過反射解析這個注解。
2.4 Target
這個注解說明了被修飾的注解的應用范圍,其用法為:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
ElementType是一個枚舉類型,它包括:
-
TYPE:類、接口、注解類型或枚舉類型。 -
PACKAGE:注解包。 -
PARAMETER:注解參數。 -
ANNOTATION_TYPE:注解 注解類型。 -
METHOD:方法。 -
FIELD:屬性(包括枚舉常量) -
CONSTRUCTOR:構造器。 -
LOCAL_VARIABLE:局部變量。
三、常見注解
3.1 @Override
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {}
告訴編譯器被修飾的方法是重寫的父類中的相同簽名的方法,編譯器會對此做出檢查,若發(fā)現父類中不存在這個方法或是存在的方法簽名不同,則會報錯。
3.2 @Deprecated
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {}
不建議使用這些被修飾的程序元素。
3.3 @SuppressWarnings
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
String[] value();
}
告訴編譯器忽略指定的警告信息。
四、自定義注解
在自定義注解前,有一些基礎知識:
- 注解類型是用
@interface關鍵字定義的。 - 所有的方法均沒有方法體,且只允許
public和abstract這兩種修飾符號,默認為public。 - 注解方法只能返回:原始數據類型,
String,Class,枚舉類型,注解,它們的一維數組。
下面是一個例子:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface MethodInfo {
String author() default "absfree";
String date();
int version() default 1;
}
五、注解的解析
5.1 編譯時解析
ButterKnife是解析編譯時注解很經典的例子,因為在Activity/ViewGroup/Fragment中,我們有很多的findViewById/setOnClickListener,這些代碼具有一個特點,就是重復性很高,它們僅僅是id和返回值不同。
這時候,我們就可以給需要執(zhí)行findViewById的View加上注解,然后在編譯時根據規(guī)則生成特定的一些類,這些類中的方法會執(zhí)行上面那些重復性的操作。
下面是網上一個大神寫的模仿ButterKnife的例子,我們來看一下編譯時解析是如果運用的。
整個項目的結構如下:

-
app:示例模塊,它和其它3個模塊的關系為:
-
viewfinder:android-library,它聲明了API的接口。 -
viewfinder-annotation:Java-library,包含了需要使用到的注解。 -
viewfinder-compiler:Java-library,包含了注解處理器。
5.1.1 創(chuàng)建注解
新建一個viewfinder-annotation的java-library,它包含了所需要用到的注解,注意到這個注解是保留到編譯時:
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BindView {
int id();
}
5.1.2 聲明API接口
新建一個viewfinder的android-library,用來提供給外部調用的接口。
首先新建一個Provider接口和它的兩個實現類:
public interface Provider {
Context getContext(Object source);
View findView(Object source, int id);
}
public class ActivityProvider implements Provider{
@Override
public Context getContext(Object source) {
return ((Activity) source);
}
@Override
public View findView(Object source, int id) {
return ((Activity) source).findViewById(id);
}
}
public class ViewProvider implements Provider {
@Override
public Context getContext(Object source) {
return ((View) source).getContext();
}
@Override
public View findView(Object source, int id) {
return ((View) source).findViewById(id);
}
}
定義接口Finder,后面我們會根據被@BindView注解所修飾的變量所在類(host)來生成不同的Finder實現類,而這個判斷的過程并不需要使用者去關心,而是由框架的實現者在編譯器時就處理好的了。
public interface Finder<T> {
/**
* @param host 持有注解的類
* @param source 調用方法的所在的類
* @param provider 執(zhí)行方法的類
*/
void inject(T host, Object source, Provider provider);
}
ViewFinder是ViewFinder框架的使用者唯一需要關心的類,當在Activity/Fragment/View中調用了inject方法時,會經過一下幾個過程:
- 獲得調用
inject方法所在類的類名xxx,也就是注解類。 - 獲得屬于該類的
xxx$$Finder,調用xxx$$Finder的inject方法。
public class ViewFinder {
private static final ActivityProvider PROVIDER_ACTIVITY = new ActivityProvider();
private static final ViewProvider PROVIDER_VIEW = new ViewProvider();
private static final Map<String, Finder> FINDER_MAP = new HashMap<>(); //由于使用了反射,因此緩存起來.
public static void inject(Activity activity) {
inject(activity, activity, PROVIDER_ACTIVITY);
}
public static void inject(View view) {
inject(view, view);
}
public static void inject(Object host, View view) {
inject(host, view, PROVIDER_VIEW);
}
public static void inject(Object host, Object source, Provider provider) {
String className = host.getClass().getName(); //獲得注解所在類的類名.
try {
Finder finder = FINDER_MAP.get(className); //每個Host類,都會有一個和它關聯的Host$$Finder類,它實現了Finder接口.
if (finder == null) {
Class<?> finderClass = Class.forName(className + "$$Finder");
finder = (Finder) finderClass.newInstance();
FINDER_MAP.put(className, finder);
}
//執(zhí)行這個關聯類的inject方法.
finder.inject(host, source, provider);
} catch (Exception e) {
throw new RuntimeException("Unable to inject for " + className, e);
}
}
}
那么這上面所有的xxx$$Finder類,到底是什么時候產生的呢,它們的inject方法里面又做了什么呢,這就需要涉及到下面注解處理器的創(chuàng)建。
5.1.3 創(chuàng)建注解處理器
創(chuàng)建viewfinder-compiler(java-library),在build.gradle中導入下面需要的類:
apply plugin: 'java'
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile project(':viewfinder-annotation')
compile 'com.squareup:javapoet:1.7.0'
compile 'com.google.auto.service:auto-service:1.0-rc2'
}
targetCompatibility = '1.7'
sourceCompatibility = '1.7'
TypeUtil定義了需要用到的類的包名和類名:
public class TypeUtil {
public static final ClassName ANDROID_VIEW = ClassName.get("android.view", "View");
public static final ClassName ANDROID_ON_LONGCLICK_LISTENER = ClassName.get("android.view", "View", "OnLongClickListener");
public static final ClassName FINDER = ClassName.get("com.example.lizejun.viewfinder", "Finder");
public static final ClassName PROVIDER = ClassName.get("com.example.lizejun.viewfinder.provider", "Provider");
}
每個BindViewField和注解類中使用了@BindView修飾的View是一一對應的關系。
public class BindViewField {
private VariableElement mFieldElement;
private int mResId;
private String mInitValue;
public BindViewField(Element element) throws IllegalArgumentException {
if (element.getKind() != ElementKind.FIELD) { //判斷被注解修飾的是否是變量.
throw new IllegalArgumentException(String.format("Only fields can be annotated with @%s", BindView.class.getSimpleName()));
}
mFieldElement = (VariableElement) element; //獲得被修飾變量.
BindView bindView = mFieldElement.getAnnotation(BindView.class); //獲得被修飾變量的注解.
mResId = bindView.id(); //獲得注解的值.
}
/**
* @return 被修飾變量的名字.
*/
public Name getFieldName() {
return mFieldElement.getSimpleName();
}
/**
* @return 被修飾變量的注解的值,也就是它的id.
*/
public int getResId() {
return mResId;
}
/**
* @return 被修飾變量的注解的值.
*/
public String getInitValue() {
return mInitValue;
}
/**
* @return 被修飾變量的類型.
*/
public TypeMirror getFieldType() {
return mFieldElement.asType();
}
}
AnnotatedClass封裝了添加被修飾注解element,通過element列表生成JavaFile這兩個過程,AnnotatedClass和注解類是一一對應的關系:
public class AnnotatedClass {
public TypeElement mClassElement;
public List<BindViewField> mFields;
public Elements mElementUtils;
public AnnotatedClass(TypeElement classElement, Elements elementUtils) {
this.mClassElement = classElement;
mFields = new ArrayList<>();
this.mElementUtils = elementUtils;
}
public String getFullClassName() {
return mClassElement.getQualifiedName().toString();
}
public void addField(BindViewField bindViewField) {
mFields.add(bindViewField);
}
public JavaFile generateFinder() {
//生成inject方法的參數.
MethodSpec.Builder methodBuilder = MethodSpec
.methodBuilder("inject") //方法名.
.addModifiers(Modifier.PUBLIC) //訪問權限.
.addAnnotation(Override.class) //注解.
.addParameter(TypeName.get(mClassElement.asType()), "host", Modifier.FINAL) //參數.
.addParameter(TypeName.OBJECT, "source")
.addParameter(TypeUtil.PROVIDER, "provider");
//在inject方法中,生成重復的findViewById(R.id.xxx)的語句.
for (BindViewField field : mFields) {
methodBuilder.addStatement(
"host.$N = ($T)(provider.findView(source, $L))",
field.getFieldName(),
ClassName.get(field.getFieldType()),
field.getResId());
}
//生成Host$$Finder類.
TypeSpec finderClass = TypeSpec
.classBuilder(mClassElement.getSimpleName() + "$$Finder")
.addModifiers(Modifier.PUBLIC)
.addSuperinterface(ParameterizedTypeName.get(TypeUtil.FINDER, TypeName.get(mClassElement.asType())))
.addMethod(methodBuilder.build())
.build();
//獲得包名.
String packageName = mElementUtils.getPackageOf(mClassElement).getQualifiedName().toString();
return JavaFile.builder(packageName, finderClass).build();
}
}
在做完前面所有的準備工作之后,后面的事情就很清楚了:
- 編譯時,系統(tǒng)會調用所有
AbstractProcessor子類的process方法,也就是調用我們的ViewFinderProcess的類。 - 在
ViewFinderProcess中,我們獲得工程下所有被@BindView注解所修飾的View。 - 遍歷這些被
@BindView修飾的View變量,獲得它們被聲明時所在的類,首先判斷是否已經為所在的類生成了對應的AnnotatedClass,如果沒有,那么生成一個,并將View封裝成BindViewField添加進入AnnotatedClass的列表,反之添加即可,所有的AnnotatedClass被保存在一個map當中。 - 當遍歷完所有被注解修飾的
View后,開始遍歷之前生成的AnnotatedClass,每個AnnotatedClass會生成一個對應的$$Finder類。 - 如果我們在
n個類中使用了@BindView來修飾里面的View,那么我們最終會得到n個$$Finder類,并且無論我們最終有沒有在這n個類中調用ViewFinder.inject方法,都會生成這n個類;而如果我們調用了ViewFinder.inject,那么最終就會通過反射來實例化它對應的$$Finder類,通過調用inject方法來給被它里面被@BindView所修飾的View執(zhí)行findViewById操作。
@AutoService(Processor.class)
public class ViewFinderProcess extends AbstractProcessor{
private Filer mFiler;
private Elements mElementUtils;
private Messager mMessager;
private Map<String, AnnotatedClass> mAnnotatedClassMap = new HashMap<>();
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init(processingEnv);
mFiler = processingEnv.getFiler();
mElementUtils = processingEnv.getElementUtils();
mMessager = processingEnv.getMessager();
}
@Override
public Set<String> getSupportedAnnotationTypes() {
Set<String> types = new LinkedHashSet<>();
types.add(BindView.class.getCanonicalName());
return types;
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
mAnnotatedClassMap.clear();
try {
processBindView(roundEnv);
} catch (IllegalArgumentException e) {
return true;
}
for (AnnotatedClass annotatedClass : mAnnotatedClassMap.values()) { //遍歷所有要生成$$Finder的類.
try {
annotatedClass.generateFinder().writeTo(mFiler); //一次性生成.
} catch (IOException e) {
return true;
}
}
return true;
}
private void processBindView(RoundEnvironment roundEnv) throws IllegalArgumentException {
for (Element element : roundEnv.getElementsAnnotatedWith(BindView.class)) {
AnnotatedClass annotatedClass = getAnnotatedClass(element);
BindViewField field = new BindViewField(element);
annotatedClass.addField(field);
}
}
private AnnotatedClass getAnnotatedClass(Element element) {
TypeElement classElement = (TypeElement) element.getEnclosingElement();
String fullClassName = classElement.getQualifiedName().toString();
AnnotatedClass annotatedClass = mAnnotatedClassMap.get(fullClassName);
if (annotatedClass == null) {
annotatedClass = new AnnotatedClass(classElement, mElementUtils);
mAnnotatedClassMap.put(fullClassName, annotatedClass);
}
return annotatedClass;
}
}
5.2 運行時解析
首先我們需要定義注解類型,RuntimeMethodInfo:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface RuntimeMethodInfo {
String author() default "tony";
String data();
int version() default 1;
}
之后,我們再定義一個類RuntimeMethodInfoTest,它其中的testRuntimeMethodInfo方法使用了這個注解,并給它其中的兩個成員變量傳入了值:
public class RuntimeMethodInfoTest {
@RuntimeMethodInfo(data = "1111", version = 2)
public void testRuntimeMethodInfo() {}
}
最后,在程序運行時,我們動態(tài)獲取注解中傳入的信息:
private void getMethodInfoAnnotation() {
Class cls = RuntimeMethodInfoTest.class;
for (Method method : cls.getMethods()) {
RuntimeMethodInfo runtimeMethodInfo = method.getAnnotation(RuntimeMethodInfo.class);
if (runtimeMethodInfo != null) {
System.out.println("RuntimeMethodInfo author=" + runtimeMethodInfo.author());
System.out.println("RuntimeMethodInfo data=" + runtimeMethodInfo.data());
System.out.println("RuntimeMethodInfo version=" + runtimeMethodInfo.version());
}
}
}
最后得到打印出的結果為:

參考文檔:
1.http://blog.csdn.net/lemon89/article/details/47836783
2.http://blog.csdn.net/hb707934728/article/details/52213086
3.https://github.com/brucezz/ViewFinder
4.http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html
