編輯:關於 Android 程式設計
獲取類類型 Class 實例有三種方式:
public static void main(String[] arg0) { String result = "Hello ReflectionText.."; System.out.println(result); Class userClass1 = User.class; Class userClass2 = new User().getClass(); try { Class userClass3 = Class .forName("idea.analyzesystem.reflection.User"); System.out.println(userClass1); System.out.println(userClass2); System.out.println(userClass3); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
我們還可以通過類類型創建實例對象(此處 newInstance 要求該類必須擁有無參構造函數):
public static void main(String[] arg0) { try { User user = User.class.newInstance(); System.out.println(user); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
類的加載分為動態加載和靜態加載。前面提到的 Class.forName("") 方法不僅用於獲取類類型,也代表動態加載。編譯時為靜態加載,運行時為動態加載,這一點在後面的注解使用中還會提及。
可以通過 class 獲取類名,既可以包含包名,也可以不包含:
public static void main(String[] arg0) { System.out.println(User.class.getSimpleName()); System.out.println(User.class.getName()); } // .................輸出結果................ User idea.analyzesystem.reflection.User
獲取一個類的所有 public 方法及其父類的所有 public 方法,可用 getMethods:
Class cls = User.class; Method[] methods = cls.getMethods();
如果想獲取本類內部定義的 private、protected 方法,可用 getDeclaredMethods(該方法不考慮訪問權限,只要是方法都會被獲取):
Method[] allSelfMethods = cls.getDeclaredMethods();
獲取方法名通過 getName 得到:
for(Method method: methods){ System.out.println(method.getName()); } //.....下面輸出User的結果................ setLevel setAge getNickName getLevel getUserName getAge getPassword getEmail setGender getIdCard setIdCard
如果需要反射得到返回值類型,可用 method.getReturnType();方法可能無參也可能帶參,可用 method.getParameterTypes() 獲取所有參數對應的類類型集合。
getFields 獲取所有 public 定義的成員變量,getDeclaredFields 則獲取所有定義的成員變量(field.getType 可獲取成員變量類型)。示例與輸出對比如下:
public static void main(String[] arg0) { Class cls = User.class; Field[] fieldspublic = cls.getFields(); for(Field field : fieldspublic){ System.out.println(field.getName()); } System.out.println("********************"); Field[] fields = cls.getDeclaredFields(); for(Field field : fields){ System.out.println(field.getName()); } } //............輸出結果................ a test ******************** a test uid userName password
獲取構造函數的名字及參數列表,可用 cls.getConstructors() 獲取所有 public 修飾的構造函數,cls.getDeclaredConstructors() 則可獲取所有修飾的構造函數。
我們可以通過 Class 獲取 Method,再通過 Method 的 invoke 方法操作對象的方法。示例代碼如下:
public static void main(String[] arg0) { User user = new User(); user.setNickName("hello"); User user2 = new User(); user2.setNickName("world"); Class cls = user.getClass(); try { Method method = cls.getDeclaredMethod("setNickName", String.class); method.invoke(user, "idea"); System.out.println(user.getNickName()); System.out.println(user2.getNickName()); } catch (Exception e) { e.printStackTrace(); } }
通過反射修改 User 對象的 setNickName,測試結果如下:
idea world
invoke 方法的返回值根據被調方法的返回值而定:void 返回 null,其他默認為 Object 類型,可按需強轉。
反射的操作都是編譯後的操作,而編譯後的泛型會被「去泛型化」。通過下面的 ArrayList 相關操作可以論證這一點:
public static void main(String[] arg0) { ArrayList list = new ArrayList<>(); ArrayList userList= new ArrayList<>(); userList.add(new User()); System.out.println(list.getClass()==userList.getClass()); } //..........輸出結果.......... true
用同樣的反射方式,可以為 userList 添加不同於 User 類型的數據,並且能添加成功:
public static void main(String[] arg0) { ArrayList list = new ArrayList<>(); ArrayList userList= new ArrayList<>(); userList.add(new User()); System.out.println(list.getClass()==userList.getClass()); try { Method method = userList.getClass().getMethod("add", Object.class); method.invoke(userList, "Test ArrayList add other type data"); System.out.println(userList.toString()); } catch (Exception e) { e.printStackTrace(); } }
輸出結果:
true [User [uid=null, userName=null, password=null, age=0, gender=null, idCard=null, level=0, nickName=null, Email=null], Test ArrayList add other type data]
事實證明,我們是可以往 List 裡添加任意類型的!理解這一點是理解後面注解的基礎。
最簡單的例子,Android 中通過 findViewById 得到控件是一件繁瑣的事情,重複寫這些代碼很累。使用注解可以把它簡化,常見的注解框架有 xUtils、ButterKnife 等。本文重點解決兩個問題:只用到 InjectView 這個功能時如何實現,以及它背後的原理是什麼——最終我們會實現一個最簡單的 ViewInject。
我們重寫父類 onCreate 方法時使用的 @Override,即表示重寫父類方法:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
如下圖所示:

setOnPageChangListener 方法在某個版本後被標記為過時(@Deprecated):
@Deprecated public void setOnPageChangeListener(OnPageChangeListener listener) { mOnPageChangeListener = listener; }
過時方法會有警告提示,我們可以在方法或類名上添加 @SuppressWarnings("Deprecated") 來忽略警告。Android 開發中因版本問題忽略警告時,需要注意版本兼容性。
按運行機制,注解可分為三大類:
源碼注解
編譯時注解
運行時注解
源碼注解只在源碼中存在,編譯成 class 後就不存在了;編譯時注解編譯成 class 後仍然存在;運行時注解則在運行階段還會起作用。(元注解是「注解的注解」,稍後再提。)
通過下面的自定義注解來認識自定義注解的要素:
@Target(ElementType.FIELD) @Inherited @TargetApi(14) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ViewInject{ int id(); int[] ids(); int age() default 18; }
@interface 表示一個注解定義,注解的方法必須是無參數的,可以有默認返回值;若只有一個方法則用 value() 表示,注解類型支持基本類型、String、Class、Annotation、Enumeration。@Target 表示注解的作用域(方法、類或字段);@Retention 控制注解的生命週期;@Inherited 表示允許被繼承;@Documented 描述注解信息;@TargetApi 指定 Android 開發中可用的最低 API 等級。若注解沒有任何成員,我們稱之為標記注解。
通過前面反射部分的學習,我們知道可以通過反射獲取類的函數與變量,並執行變量賦值與方法調用。cls.isAnnotationPresent(xx.class) 用於判斷是否存在指定類型的注解,Method 同樣支持這個方法。下面看看 xUtils 使用的注解代碼(實際開發中 ViewUtils.inject 初始化方法通常放在基類,實現類 Activity 甚至無需重寫 onCreate):
@ContentView(R.layout.activity_splash) public class MainActivity extends Activity{ @ViewInject(R.id.button_login) private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ViewUtils.inject(this); } @OnClick(R.id.button_login) public void onClick(View v){ } @OnClick({R.id.button_login,R.id.searchView}) public void onClicks(View v){ } }
ViewUtils.inject(this) 在內部做解析操作。先來看看 ContentView 的定義:
package com.lidroid.xutils.view.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ContentView { int value(); }
在 inject 方法調用後,解析類名上注解的代碼是這樣的:
@SuppressWarnings("ConstantConditions") private static void injectObject(Object handler, ViewFinder finder) { Class handlerType = handler.getClass(); // 判斷是否存在ContentView注解,如果存在,通過注入的方式setContentView(int) ContentView contentView = handlerType.getAnnotation(ContentView.class); if (contentView != null) { try { Method setContentViewMethod = handlerType.getMethod("setContentView", int.class); setContentViewMethod.invoke(handler, contentView.value()); } catch (Throwable e) { LogUtils.e(e.getMessage(), e); } }
再看 onClick 的注解實現。首先有一個作用於注解的 EventBase 注解:
/** * Author: wyouflf * Date: 13-9-9 * Time: 下午12:43 */ @Target(ElementType.ANNOTATION_TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface EventBase { Class listenerType(); String listenerSetter(); String methodName(); }
OnClick 注解定義如下(指定了設置 OnClickListener 的方法名與回調方法名,支持一次注解多個控件,value 表示 view 的 id 值):
/** * Author: wyouflf * Date: 13-8-16 * Time: 下午2:27 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @EventBase( listenerType = View.OnClickListener.class, listenerSetter = "setOnClickListener", methodName = "onClick") public @interface OnClick { int[] value(); int[] parentId() default 0; }
解析這些方法注解的 ViewUtils 源碼如下:
// inject event Method[] methods = handlerType.getDeclaredMethods();//獲取所有方法 if (methods != null && methods.length > 0) { for (Method method : methods) { Annotation[] annotations = method.getDeclaredAnnotations();//獲取所有的方法上面的注解 if (annotations != null && annotations.length > 0) { for (Annotation annotation : annotations) { Class annType = annotation.annotationType(); if (annType.getAnnotation(EventBase.class) != null) {//如果存在EventBase注解 method.setAccessible(true); try { // ProGuard:-keep class * extent java.lang.annotation.Annotation { *; } //如果使用了注解要添加混淆規則,保證注解不能被混淆 Method valueMethod = annType.getDeclaredMethod("value"); Method parentIdMethod = null; try { parentIdMethod = annType.getDeclaredMethod("parentId"); } catch (Throwable e) { } Object values = valueMethod.invoke(annotation); Object parentIds = parentIdMethod == null ? null : parentIdMethod.invoke(annotation); int parentIdsLen = parentIds == null ? 0 : Array.getLength(parentIds); int len = Array.getLength(values); for (int i = 0; i < len; i++) { ViewInjectInfo info = new ViewInjectInfo(); info.value = Array.get(values, i); info.parentId = parentIdsLen > i ? (Integer) Array.get(parentIds, i) : 0; EventListenerManager.addEventMethod(finder, info, annotation, handler, method); } } catch (Throwable e) { LogUtils.e(e.getMessage(), e); } } } } } }
ViewInject 注解的定義如下(不得不說 value 只支持單個控件,個人認為支持批量注解會減少很多代碼,有興趣的讀者可以嘗試改進):
package com.lidroid.xutils.view.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD)//作用在字段上面 @Retention(RetentionPolicy.RUNTIME) //運行時仍然有效,如果改為class或者編譯時就會有問題,findById找不到 //變量為空引用時拋出空指針異常,如果混淆了注解,也會導致找不到控件 public @interface ViewInject { int value(); /* parent view id */ int parentId() default 0; }
注解變量的解析在 ViewUtils 中的實現如下:
private static void injectObject(Object handler, ViewFinder finder) { //...................略................... Field[] fields = handlerType.getDeclaredFields();//查找出所有控件變量 if (fields != null && fields.length > 0) { for (Field field : fields) { //控件變量注解找到後通過finder提供的findById獲取控件實例 ViewInject viewInject = field.getAnnotation(ViewInject.class); if (viewInject != null) { try { View view = finder.findViewById(viewInject.value(), viewInject.parentId()); //打開權限然後用反射賦值 if (view != null) { field.setAccessible(true); field.set(handler, view); } } catch (Throwable e) { //如果用ViewInject注解了但是找不到視圖的話直接拋出了運行時異常 LogUtils.e(e.getMessage(), e); } } else { //..............略過其他注解解析................ } } } }
通過對反射與注解的系統學習,我們可以把代碼玩得更透徹,再也不用為看不懂別人的注解代碼而發愁。此外,我們也可以通過注解的方式創建數據庫表、實現對 SQLite 表數據的增刪改查。雖然當前多數項目採用第三方的 SQLite 開源庫,但了解注解的這種實現方式仍然很有價值,xUtils 的 db 模塊就是很好的參考。儘管 xUtils 目前也不再維護、已推出 xUtils 3.0,但我們不能否認它是一個非常優秀的開源項目。
源碼解析 Android Adapter 家族:BaseAdapter、ArrayAdapter、SimpleAdapter 與 SimpleCursorAdapter
Adapter 相當於一個資料源,為 AdapterView 提供資料並據此產生對應的 UI;透過呼叫 AdapterView 的 setAdapter 方法,就能把 A
Android 自訂 ProgressDialog 進度對話框完整用法
系統內建的對話框樣式單一,很多時候需要呈現自訂的圖示、文字與進度型態。ProgressDialog 就是為此而生:它讓你決定對話框裡到底要顯示什麼。 常用方法速查 se
ImageView 屬性 android:scaleType 的作用分析
網路上關於 scaleType 的說明大多是互相轉抄,讀起來反而更糊塗。以下依據 API 文件的定義逐一整理,並用同一張測試圖說明各值的實際差異。 基本用法 <I
Android Spinner 下拉選單自訂:ArrayAdapter 與自訂 Adapter 兩種做法
Spinner 相當於一個下拉式清單,是表單類介面中相當實用的元件。它本身只負責呈現,資料的綁定與樣式全靠 Adapter 決定。本文示範兩種常見路徑:先用系統提供的 A