Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入解讀 Android 中的注解與反射

編輯:關於 Android 程式設計

前言

近段時間在研究 EventBus 和 Retrofit 的過程中,反覆遇到注解這個概念。由於當年學 Java 時對這塊沒太深入,看相關代碼總有點雲裡霧裡,於是借這篇文章把注解和反射的用法梳理一遍。

我們先從反射說起,理解它的意義與用法後,再看注解的使用,最後說明 Android 開發中如何把兩者結合起來。

反射

Java 反射(Reflection)定義

Java 反射機制是指在運行狀態下:

對於任意一個類,都能知道它的所有屬性和方法;
對於任意一個對象,都能調用它的任何方法和屬性。

這種動態獲取類信息、動態調用對象方法的能力,就叫做反射。比如:

 // 獲取類
 Class c = Class.forName("java.lang.String");
 // 獲取所有的屬性
 Field[] fields = c.getDeclaredFields();
 StringBuffer sb = new StringBuffer();
 sb.append(Modifier.toString(c.getModifiers()) + " class " + c.getSimpleName() + "{\n");
 // 遍歷每一個屬性
 for (Field field : fields) {
     sb.append("\t");// 空格
     sb.append(Modifier.toString(field.getModifiers()) + " ");// 修飾符,如 public、static
     sb.append(field.getType().getSimpleName() + " ");// 屬性類型名
     sb.append(field.getName() + ";\n");// 屬性名 + 回車
 }
 sb.append("}\n");
 System.out.println(sb);

這樣就能拿到我們常用的 String 類的所有屬性:

再比如獲取所有方法:

 // 獲取類
 Class c = Class.forName("java.lang.String");
 // 獲取所有的方法
 Method[] ms = c.getDeclaredMethods();
 // 遍歷輸出所有方法
 for (Method method : ms) {
     // 獲取方法的所有參數
     Parameter[] parameters = method.getParameters();
     String params = "";
     if (parameters.length > 0) {
         StringBuffer stringBuffer = new StringBuffer();
         for (Parameter parameter : parameters) {
             stringBuffer.append(parameter.getType().getSimpleName() + " " + parameter.getName() + ",");
         }
         // 去掉最後一個逗號
         params = stringBuffer.substring(0, stringBuffer.length() - 1);
     }
     System.err.println(Modifier.toString(method.getModifiers()) + " " + method.getReturnType().getSimpleName() + " " + method.getName() + " (" + params + ")");
 }

可以拿到 String 類的所有方法(下圖只截取部分):

Java 反射機制 API

主要的幾個類

Java 中與反射相關的核心類有:

類 用途 java.lang.Class 編譯後 class 文件的對象
java.lang.reflect.Constructor 構造方法
java.lang.reflect.Field 類的成員變量(屬性)
java.lang.reflect.Method 類的成員方法
java.lang.reflect.Modifier 判斷方法類型
java.lang.annotation.Annotation 類的注解

具體實現

為方便描述,先創建一個類 TestClass:

 public class TestClass {
     private String address;
     private String port;
     private int number;
     public void printInfo() {
         System.out.println("info is " + address + ":" + port);
     }
     private void myMethod(int number, String sex) { }
     public String getPort() { return port; }
     public void setPort(String port) { this.port = port; }
     public String getAddress() { return address; }
     public void setAddress(String address) { this.address = address; }
     public int getNumber() { return number; }
     public void setNumber(int number) { this.number = number; }
 }

這個類很簡單,包含 address、port、number 三個成員變量及各自的 get/set 方法,還有兩個自定義方法 printInfo() 和 myMethod()。下面看看如何通過反射獲取它的所有「信息」。

1. 獲取 Class,有三種寫法:

 // 獲取類的三種方法
 Class c = Class.forName("java.lang.String"); // 需用完整包名
 Class c1 = String.class;
 String str = new String();
 Class c2 = str.getClass();

這裡的 c、c1、c2 是相等的,反射中一般用第一種寫法。

2. 獲取類的屬性(成員變量):

 Field[] fields = c.getDeclaredFields();

返回一個數組,包含所有屬性。每個 Field 都提供了一系列方法可讀取或修改其內容:

 // 遍歷每一個屬性
 for (Field field : fields) {
     sb.append("\t");
     sb.append(Modifier.toString(field.getModifiers()) + " ");
     sb.append(field.getType().getSimpleName() + " ");
     sb.append(field.getName() + ";\n");
 }

這樣就能得到 TestClass 的所有屬性:

3. 獲取類的方法:

 // 獲取所有的方法
 Method[] ms = c.getDeclaredMethods();

與屬性類似,我們仍能通過一系列方法拿到方法的返回值類型、名稱與參數:

同樣能獲取到 TestClass 的所有方法:

可以看到,反射取到的屬性和方法與我們定義的完全一致。順手調用一下 printInfo:

 new TestClass().printInfo();

由於屬性未初始化,輸出如下:

由此可見,利用反射能很方便地「反編譯」一個 class。那麼這麼做的意義何在?別急,先了解注解。

Java 注解(Annotation)

什麼是注解

關於注解的定義網上說法很多,這裡只強調兩點。

Annotation 是 Java 提供的一種為源程序元素關聯任意信息或元數據(metadata)的途徑。

注解是被動的元數據,本身永遠不會有主動行為。

既然是被動數據,對於 Override 這類已有注解,我們只能看著它,卻不清楚其內部機制;所以要理解注解,最好直接從自定義注解入手。

自定義注解

 @Retention(RetentionPolicy.RUNTIME)
 @Target({ElementType.FIELD})
 @Documented
 @Inherited
 public @interface Bind {
     int value() default 1;
     boolean canBeNull() default false;
 }

這就是自定義注解的形式:用 @interface 聲明一個注解。注解只有成員變量而沒有方法,其成員以「無形參的方法」形式聲明——方法名即成員名,返回值即成員類型,例如上面的 value 和 canBeNull。

元注解

自定義注解裡還能再套注解,修飾注解的注解就稱為元注解。

@Retention

@Retention 用來標記自定義注解的有效範圍,取值有三種:

RetentionPolicy.SOURCE:只在源代碼中保留,一般用於提升代碼可讀性或輔助代碼檢查,比如 Override;

RetentionPolicy.CLASS:默認值,能保留到編譯後的字節碼 class 文件中,但運行時無法獲取;

RetentionPolicy.RUNTIME:既保留到字節碼文件,又能在運行時通過反射獲取,這也是最常用的。

@Target

@Target 指定注解可用於修飾哪些程序元素,它含有一個 ElementType[] 類型的 value 成員,枚舉值如下:

ElementType.TYPE:類、接口或枚舉
ElementType.FIELD:成員變量
ElementType.METHOD:方法
ElementType.PARAMETER:參數
ElementType.CONSTRUCTOR:構造器
ElementType.LOCAL_VARIABLE:局部變量
ElementType.ANNOTATION_TYPE:注解
ElementType.PACKAGE:包

使用了 @Documented 的注解可以出現在 javadoc 中;
使用了 @Inherited 表示注解內容可被子類繼承。

關於注解就說到這裡。

反射 & 注解的使用

屬性值使用注解

先自定義兩個注解 BindPort 和 BindAddress:

 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.FIELD)
 public @interface BindPort {
     String value() default "8080";
 }

它保留到運行時,可修飾成員變量,含一個默認值為「8080」的成員。

 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.FIELD)
 public @interface BindAddress {
     String value() default "127.0.0.0";
 }

與上面類似,只是默認值為「127.0.0.0」。同時修改 TestClass:

 public class TestClass {
     @BindAddress() String address;
     @BindPort() private String port;
     private int number;
     public void printInfo() {
         System.out.println("info is " + address + ":" + port);
     }
     ........ 
 }

由於定義注解時給了默認值,這裡可以不寫參數。

使用反射獲取注解信息

前面說過,注解是被動的元數據,永遠不會有主動行為,所以要靠反射才能讓它產生意義。通過反射既能拿到所有屬性和方法,獲取注解信息自然也不在話下:

 // 獲取類
 Class c = Class.forName(className);
 // 實例化一個 TestClass 對象
 TestClass tc = (TestClass) c.newInstance();
 // 獲取所有的屬性
 Field[] fields = c.getDeclaredFields();
 for (Field field : fields) {
     if (field.isAnnotationPresent(BindPort.class)) {
         BindPort port = field.getAnnotation(BindPort.class);
         field.setAccessible(true);
         field.set(tc, port.value());
     }
     if (field.isAnnotationPresent(BindAddress.class)) {
         BindAddress address = field.getAnnotation(BindAddress.class);
         field.setAccessible(true);
         field.set(tc, address.value());
     }
 }
 tc.printInfo();

運行後輸出如下:

邏輯很簡單:遍歷所有屬性,若當前屬性被指定注解修飾,就把它的值改為注解成員的值。這裡找到被 BindPort 修飾的屬性,把 value 賦給它。之所以調用 setAccessible(true),是因為 port 聲明為 private,這樣做能確保訪問不報錯。

嚴格說這樣並不安全,也不符合面向對象思想,這裡只是為了舉例說明。不過你也會發現,反射確實提供了一種在運行時改變對象的能力。

繼續修改 TestClass:

 public class TestClass {
     @BindAddress("https://www.google.com.cn") String address;
     @BindPort("8888") private String port;
     private int number;
     public void printInfo() {
         System.out.println("info is " + address + ":" + port);
     }
     .......
 }

這次為注解設定了參數,再次運行,結果應該不難猜:

由於給成員變量加注解時寫了參數,反射時也取到了相應的值。

方法使用注解

對屬性加注解可能還不足以讓你體會注解 & 反射的威力,我們再來看看給方法加注解的效果。先定義一個注解:

 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.METHOD)
 public @interface BindGet {
     String value() default "";
 }

有效範圍至運行時,適用於方法。再次修改 TestClass:

 public class TestClass {
     @BindAddress("https://www.google.com.cn") String address;
     @BindPort("8888") private String port;
     private int number;
     @BindGet("mike") void getHttp(String param) {
         String url = "https://www.baidu.com/?username" + param;
         System.err.println("get------->" + url);
     }
     ...........
 }

新增了一個由 @BindGet 修飾的 getHttp 方法。再看反射的用法:

 // 獲取類
 Class c = Class.forName(className);
 TestClass tc = (TestClass) c.newInstance();
 // 獲取所有的方法
 Method[] ms = c.getDeclaredMethods();
 for (Method method : ms) {
     if (method.isAnnotationPresent(BindGet.class)) {
         BindGet bindGet = method.getAnnotation(BindGet.class);
         String param = bindGet.value();
         method.invoke(tc, param);
     }
 }

邏輯和解析屬性時相似:判斷當前方法是否被 BindGet 修飾,若是,就用注解中的參數作為當前方法的參數去調用它。這樣運行時通過反射就能主動調用 getHttp:

於是,我們便能通過注解動態修改 username 參數,甚至整個 http 請求地址(假設 getHttp 是用來發網絡請求的)。

到這裡,你應該已經學會如何用反射獲取注解信息,但也一定會疑惑:這麼做到底有什麼用?答案就是兩個字——動態。這正是注解與反射最大的意義:我們能在運行時動態地訪問對象。

說了這麼多,來看看 Android 開發中我們常見的注解與反射。

Android 中的注解 & 反射

ButterKnife

如果你是 Android 開發者,在用上 ButterKnife 之前,一定寫過無數次 findViewById。而用了它之後,findViewById 甚至 setOnClickListener 都能省下不少功夫:

 public class ButtferknifeDemoActivity extends AppCompatActivity {
     @BindView(R.id.textView) TextView textView;
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_buttferknife);
         ButterKnife.bind(this);
         textView.setText("I'm not null");
     }
 }

當佈局中控件很多時,這樣做能省下大量時間。看看 BindView 的定義:

 @Retention(CLASS)
 @Target(FIELD)
 public @interface BindView {
     /** View ID to which the field will be bound. */
     @IdRes int value();
 }

它用於修飾變量,有效範圍限定到 CLASS(編譯階段),並未到運行時。在 ButterKnife(8.4.0)源碼中可以看到:

 /** Simpler version of {@link View#findViewById(int)} which infers the target type. */
 @SuppressWarnings({ "unchecked", "UnusedDeclaration" })
 @CheckResult
 public static <T extends View> T findById(@NonNull View view, @IdRes int id) {
     return (T) view.findViewById(id);
 }

可以推斷,編譯期最終還是走到 view.findViewById(id)。正是注解與反射(及編譯期處理)的結合,讓我們免去了大量重複勞動。

Retrofit 2.0

第一次用 Retrofit,我完全被它這種「接口即定義」的寫法搞暈了:參數怎麼傳?@ 又是什麼意思?帶著這些疑問,先看這裡用到的兩個注解。

 public interface UserBasicService {
     @GET("users/{user}")
     Call<ResponseBody> getUsers(@Path("user") String uses);
 }

GET

 /** Make a GET request. */
 @Documented
 @Target(METHOD)
 @Retention(RUNTIME)
 public @interface GET {
     /** A relative or absolute path, or full URL of the endpoint. */
     String value() default "";
 }

Path

 @Documented
 @Retention(RUNTIME)
 @Target(PARAMETER)
 public @interface Path {
     String value();
     /** Specifies whether the argument value is already URL encoded. */
     boolean encoded() default false;
 }

這兩個注解的生命週期都延續到了 RUNTIME(運行時):GET 用於方法,Path 用於參數,與我們定義的 getUsers() 一致。至於 Retrofit 中反射與注解的深層用法,涉及動態代理,這裡不展開——總思路是根據注解參數動態生成 Request,再交由 OkHttp 發起調用,以後再做深入分析。

後話

以合適的方式使用反射,會讓寫代碼的方式更加靈活;但若使用不當,反而會適得其反,影響性能。不過 EventBus、Retrofit 的火爆,讓我們有理由相信,在如今硬件配置堪比電腦的手機上,這點開銷也許可以忽略不計。所以反射的使用,還是仁者見仁、智者見智吧。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved