一、什么是注解
注解可以向編譯器、虛擬機(jī)等解釋說明一些事情。舉一個(gè)最常見的例子,當(dāng)我們?cè)谧宇惍?dāng)中覆寫父類的aMethod
方法時(shí),在子類的aMethod
上會(huì)用@Override
來修飾它,反之,如果我們給子類的bMethod
用@Override
注解修飾,但是在它的父類當(dāng)中并沒有這個(gè)bMethod
,那么就會(huì)報(bào)錯(cuò)。這個(gè)@Override
就是一種注解,它的作用是告訴編譯器它所注解的方法是重寫父類的方法,這樣編譯器就會(huì)去檢查父類是否存在這個(gè)方法。
注解是用來描述Java
代碼的,它既能被編譯器解析,也能在運(yùn)行時(shí)被解析。
二、元注解
元注解是描述注解的注解,也是我們編寫自定義注解的基礎(chǔ),比如以下代碼中我們使用@Target
元注解來說明MethodInfo
這個(gè)注解只能應(yīng)用于對(duì)方法進(jìn)行注解:
@Target(ElementType.METHOD)
public @interface MethodInfo {
//....
}
下面我們來介紹4種元注解,我們可以發(fā)現(xiàn)這四個(gè)元注解的定義又借助到了其它的元注解:
2.1 Documented
當(dāng)一個(gè)注解類型被@Documented
元注解所描述時(shí),那么無論在哪里使用這個(gè)注解,都會(huì)被Javadoc
工具文檔化,我們來看以下它的定義:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
//....
}
- 定義注解時(shí)使用
@interface
關(guān)鍵字: -
@Document
表示它本身也會(huì)被文檔化; -
Retention
表示@Documented
這個(gè)注解能保留到運(yùn)行時(shí); -
@ElementType.ANNOTATION_TYPE
表示@Documented
這個(gè)注解只能夠被用來描述注解類型。
2.2 Inherited
表明被修飾的注解類型是自動(dòng)繼承的,若一個(gè)注解被Inherited
元注解修飾,則當(dāng)用戶在一個(gè)類聲明中查詢?cè)撟⒔忸愋蜁r(shí),若發(fā)現(xiàn)這個(gè)類聲明不包含這個(gè)注解類型,則會(huì)自動(dòng)在這個(gè)類的父類中查詢相應(yīng)的注解類型。
我們需要注意的是,用inherited
修飾的注解,它的這種自動(dòng)繼承功能,只能對(duì)類生效,對(duì)方法是不生效的。也就是說,如果父類有一個(gè)aMethod
方法,并且該方法被注解a
修飾,那么無論這個(gè)注解a
是否被Inherited
修飾,只要我們?cè)谧宇愔懈矊懥?code>aMethod,子類的aMethod
都不會(huì)繼承父類aMethod
的注解,反之,如果我們沒有在子類中覆寫aMethod
,那么通過子類我們依然可以獲得注解a
。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
//....
}
2.3 Retention
這個(gè)注解表示一個(gè)注解類型會(huì)被保留到什么時(shí)候,它的原型為:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
RetentionPolicy value();
}
其中,RetentionPolicy.xxx
的取值有:
-
SOURCE
:表示在編譯時(shí)這個(gè)注解會(huì)被移除,不會(huì)包含在編譯后產(chǎn)生的class
文件中。 -
CLASS
:表示這個(gè)注解會(huì)被包含在class
文件中,但在運(yùn)行時(shí)會(huì)被移除。 -
RUNTIME
:表示這個(gè)注解會(huì)被保留到運(yùn)行時(shí),我們可以在運(yùn)行時(shí)通過反射解析這個(gè)注解。
2.4 Target
這個(gè)注解說明了被修飾的注解的應(yīng)用范圍,其用法為:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
ElementType
是一個(gè)枚舉類型,它包括:
-
TYPE
:類、接口、注解類型或枚舉類型。 -
PACKAGE
:注解包。 -
PARAMETER
:注解參數(shù)。 -
ANNOTATION_TYPE
:注解 注解類型。 -
METHOD
:方法。 -
FIELD
:屬性(包括枚舉常量) -
CONSTRUCTOR
:構(gòu)造器。 -
LOCAL_VARIABLE
:局部變量。
三、常見注解
3.1 @Override
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {}
告訴編譯器被修飾的方法是重寫的父類中的相同簽名的方法,編譯器會(huì)對(duì)此做出檢查,若發(fā)現(xiàn)父類中不存在這個(gè)方法或是存在的方法簽名不同,則會(huì)報(bào)錯(cuò)。
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();
}
告訴編譯器忽略指定的警告信息。
四、自定義注解
在自定義注解前,有一些基礎(chǔ)知識(shí):
- 注解類型是用
@interface
關(guān)鍵字定義的。 - 所有的方法均沒有方法體,且只允許
public
和abstract
這兩種修飾符號(hào),默認(rèn)為public
。 - 注解方法只能返回:原始數(shù)據(jù)類型,
String
,Class
,枚舉類型,注解,它們的一維數(shù)組。
下面是一個(gè)例子:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface MethodInfo {
String author() default "absfree";
String date();
int version() default 1;
}
五、注解的解析
5.1 編譯時(shí)解析
ButterKnife
是解析編譯時(shí)注解很經(jīng)典的例子,因?yàn)樵?code>Activity/ViewGroup/Fragment中,我們有很多的findViewById/setOnClickListener
,這些代碼具有一個(gè)特點(diǎn),就是重復(fù)性很高,它們僅僅是id
和返回值不同。
這時(shí)候,我們就可以給需要執(zhí)行findViewById
的View
加上注解,然后在編譯時(shí)根據(jù)規(guī)則生成特定的一些類,這些類中的方法會(huì)執(zhí)行上面那些重復(fù)性的操作。
下面是網(wǎng)上一個(gè)大神寫的模仿ButterKnife
的例子,我們來看一下編譯時(shí)解析是如果運(yùn)用的。
整個(gè)項(xiàng)目的結(jié)構(gòu)如下:
-
app
:示例模塊,它和其它3個(gè)模塊的關(guān)系為:
-
viewfinder
:android-library
,它聲明了API
的接口。 -
viewfinder-annotation
:Java-library
,包含了需要使用到的注解。 -
viewfinder-compiler
:Java-library
,包含了注解處理器。
5.1.1 創(chuàng)建注解
新建一個(gè)viewfinder-annotation
的java-library
,它包含了所需要用到的注解,注意到這個(gè)注解是保留到編譯時(shí):
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface BindView {
int id();
}
5.1.2 聲明API
接口
新建一個(gè)viewfinder
的android-library
,用來提供給外部調(diào)用的接口。
首先新建一個(gè)Provider
接口和它的兩個(gè)實(shí)現(xiàn)類:
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
,后面我們會(huì)根據(jù)被@BindView
注解所修飾的變量所在類(host
)來生成不同的Finder
實(shí)現(xiàn)類,而這個(gè)判斷的過程并不需要使用者去關(guān)心,而是由框架的實(shí)現(xiàn)者在編譯器時(shí)就處理好的了。
public interface Finder<T> {
/**
* @param host 持有注解的類
* @param source 調(diào)用方法的所在的類
* @param provider 執(zhí)行方法的類
*/
void inject(T host, Object source, Provider provider);
}
ViewFinder
是ViewFinder
框架的使用者唯一需要關(guān)心的類,當(dāng)在Activity/Fragment/View
中調(diào)用了inject
方法時(shí),會(huì)經(jīng)過一下幾個(gè)過程:
- 獲得調(diào)用
inject
方法所在類的類名xxx
,也就是注解類。 - 獲得屬于該類的
xxx$$Finder
,調(diào)用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); //每個(gè)Host類,都會(huì)有一個(gè)和它關(guān)聯(lián)的Host$$Finder類,它實(shí)現(xiàn)了Finder接口.
if (finder == null) {
Class<?> finderClass = Class.forName(className + "$$Finder");
finder = (Finder) finderClass.newInstance();
FINDER_MAP.put(className, finder);
}
//執(zhí)行這個(gè)關(guān)聯(lián)類的inject方法.
finder.inject(host, source, provider);
} catch (Exception e) {
throw new RuntimeException("Unable to inject for " + className, e);
}
}
}
那么這上面所有的xxx$$Finder
類,到底是什么時(shí)候產(chǎn)生的呢,它們的inject
方法里面又做了什么呢,這就需要涉及到下面注解處理器的創(chuàng)建。
5.1.3 創(chuàng)建注解處理器
創(chuàng)建viewfinder-compiler
(java-library
),在build.gradle
中導(dǎo)入下面需要的類:
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");
}
每個(gè)BindViewField
和注解類中使用了@BindView
修飾的View
是一一對(duì)應(yīng)的關(guān)系。
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
這兩個(gè)過程,AnnotatedClass
和注解類是一一對(duì)應(yīng)的關(guān)系:
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方法的參數(shù).
MethodSpec.Builder methodBuilder = MethodSpec
.methodBuilder("inject") //方法名.
.addModifiers(Modifier.PUBLIC) //訪問權(quán)限.
.addAnnotation(Override.class) //注解.
.addParameter(TypeName.get(mClassElement.asType()), "host", Modifier.FINAL) //參數(shù).
.addParameter(TypeName.OBJECT, "source")
.addParameter(TypeUtil.PROVIDER, "provider");
//在inject方法中,生成重復(fù)的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();
}
}
在做完前面所有的準(zhǔn)備工作之后,后面的事情就很清楚了:
- 編譯時(shí),系統(tǒng)會(huì)調(diào)用所有
AbstractProcessor
子類的process
方法,也就是調(diào)用我們的ViewFinderProcess
的類。 - 在
ViewFinderProcess
中,我們獲得工程下所有被@BindView
注解所修飾的View
。 - 遍歷這些被
@BindView
修飾的View
變量,獲得它們被聲明時(shí)所在的類,首先判斷是否已經(jīng)為所在的類生成了對(duì)應(yīng)的AnnotatedClass
,如果沒有,那么生成一個(gè),并將View
封裝成BindViewField
添加進(jìn)入AnnotatedClass
的列表,反之添加即可,所有的AnnotatedClass
被保存在一個(gè)map
當(dāng)中。 - 當(dāng)遍歷完所有被注解修飾的
View
后,開始遍歷之前生成的AnnotatedClass
,每個(gè)AnnotatedClass
會(huì)生成一個(gè)對(duì)應(yīng)的$$Finder
類。 - 如果我們?cè)?code>n個(gè)類中使用了
@BindView
來修飾里面的View
,那么我們最終會(huì)得到n
個(gè)$$Finder
類,并且無論我們最終有沒有在這n
個(gè)類中調(diào)用ViewFinder.inject
方法,都會(huì)生成這n
個(gè)類;而如果我們調(diào)用了ViewFinder.inject
,那么最終就會(huì)通過反射來實(shí)例化它對(duì)應(yīng)的$$Finder
類,通過調(diào)用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 運(yùn)行時(shí)解析
首先我們需要定義注解類型,RuntimeMethodInfo
:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface RuntimeMethodInfo {
String author() default "tony";
String data();
int version() default 1;
}
之后,我們?cè)俣x一個(gè)類RuntimeMethodInfoTest
,它其中的testRuntimeMethodInfo
方法使用了這個(gè)注解,并給它其中的兩個(gè)成員變量傳入了值:
public class RuntimeMethodInfoTest {
@RuntimeMethodInfo(data = "1111", version = 2)
public void testRuntimeMethodInfo() {}
}
最后,在程序運(yùn)行時(shí),我們動(dòng)態(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());
}
}
}
最后得到打印出的結(jié)果為:
參考文檔:
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