編輯:Android 開發實例
所謂反射(Reflection),指的是程式在執行階段仍能「看清自己」的能力:對於任意一個類別,我們可以取得它的全部欄位與方法;對於任意一個物件,我們也可以動態地呼叫它身上的方法。這種在執行期才決定要操作誰、要呼叫什麼的機制,就是 Java 反射。
反射主要帶來幾種能力:在執行期判斷某個物件屬於哪個類別、動態建立任意類別的物件、讀取該類別的成員變數與方法、呼叫任意物件的方法,以及產生動態代理。
我們常把動態綁定、動態連結、動態載入掛在嘴邊,但「動態」從來沒有一個放諸四海皆準的嚴格定義,工程師社群往往各說各話。比較被接受的說法是:如果一個語言允許在執行時改變程式結構或變數型別,它就是動態語言。用這個標準看,Perl、Python、Ruby 算動態語言,而 C++、Java、C# 不算。
有趣的是,Java 雖然被歸在「非動態」那一側,卻擁有一個極為亮眼的動態機制——Reflection。這個字本意是反射、倒影,用在 Java 身上,意思是我們可以在執行期載入、探查並使用那些在編譯時完全未知的類別。也就是說,程式可以載入一個名稱到執行時才知道的 class,摸清它的完整結構,建立物件實體、為欄位設值、或呼叫它的方法。這種「看透 class」的能力,也被稱為 introspection(內省)。Reflection 與 introspection 這兩個術語經常被並肩提起。
Android 平台上有大量類別是被刻意隱藏、不對外開放的,ServiceManager、藍牙模組等就是典型例子,其中牽涉到的 class 數量相當可觀。想正常使用這些被藏起來的 API,反射往往是最實際的途徑——把類別轉成物件後再操作。由於 Android 應用本身就是以 Java 為基礎,反射這套本領自然也完整可用。
下面我用一個小 DEMO 說明如何透過反射,依「方法名稱」動態調用類別中的方法,完成一台加減乘除計算機。
先寫一個最樸素的類別,裡面只有四個方法,分別負責加、減、乘、除:
class operationClass {
public float add(int parm1, int parm2) {
return parm1 + parm2;
}
public float cut(int parm1, int parm2) {
return parm1 - parm2;
}
public float ride(int parm1, int parm2) {
return parm1 * parm2;
}
public float Except(int parm1, int parm2) {
return parm1 / parm2;
}
}
兩個輸入框、一個顯示結果的文字元件,再加上四個運算按鈕與一個等號按鈕:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent">
<EditText android:id="@+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></EditText>
<EditText android:id="@+id/EditText02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></EditText>
<TextView android:id="@+id/TextView01"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<LinearLayout android:id="@+id/LinearLayout01"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:text="+" android:id="@+id/Button01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="-" android:id="@+id/Button02"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="*" android:id="@+id/Button03"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="/" android:id="@+id/Button04"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="=" android:id="@+id/Button05"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
</LinearLayout>
這篇是反射的入門篇,所以只示範最常用的幾個 API。整個流程可以拆成四步。
1. 取得類別物件
Class<?> classType = Class.forName("com.terry.operationClass");
如果你已經確定類別名稱、而且它就存在於自己的專案(或 jar 檔)裡,也可以寫得更直接:
Class<?> classType = operationClass.class;
2. 建立該類別的物件實體
Object invokeOperation = classType.newInstance();
3. 依名稱與參數型別找出方法
Method addMethod = classType.getMethod("add", new Class[] {
int.class, int.class });
第一個參數是要找的方法名稱,第二個參數則用來指定該方法的參數型別。
4. 呼叫並取得回傳值
Object result = addMethod.invoke(invokeOperation, new Object[] {
new Integer(first), new Integer(second) });
拿到 Method 物件後呼叫 invoke,方法體裡的邏輯就會實際執行,回傳值以 Object 形式交回我們手上。
提醒:反射相當耗用系統資源,非必要不建議使用,行動裝置這類資源緊絀的環境更要三思。
package com.terry;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class OperationActivity extends Activity {
private EditText one, two;
private TextView result;
private Button add, cut, ride, Except, sum;
int first, second;
String operaionFun = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findview();
add.setOnClickListener(click);
cut.setOnClickListener(click);
ride.setOnClickListener(click);
Except.setOnClickListener(click);
sum.setOnClickListener(click);
}
void findview() {
one = (EditText) findViewById(R.id.EditText01);
two = (EditText) findViewById(R.id.EditText02);
result = (TextView) findViewById(R.id.TextView01);
add = (Button) findViewById(R.id.Button01);
cut = (Button) findViewById(R.id.Button02);
ride = (Button) findViewById(R.id.Button03);
Except = (Button) findViewById(R.id.Button04);
sum = (Button) findViewById(R.id.Button05);
}
OnClickListener click = new OnClickListener() {
@Override
public void onClick(View v) {
first = Integer.parseInt(one.getText().toString());
second = Integer.parseInt(two.getText().toString());
switch (v.getId()) {
case R.id.Button01:
operaionFun = "+";
break;
case R.id.Button02:
operaionFun = "-";
break;
case R.id.Button03:
operaionFun = "*";
break;
case R.id.Button04:
operaionFun = "/";
break;
case R.id.Button05:
try {
result.setText(operation(operaionFun, first, second));
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
break;
}
}
};
String operation(String oper, int first, int second)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InvocationTargetException {
// 取得類別物件
Class<?> classType = Class.forName("com.terry.operationClass");
// 若類別就在本工程內,也可寫成:operationClass.class
Object invokeOperation = classType.newInstance();
if (oper.equals("+")) {
Method addMethod = classType.getMethod("add", new Class[] {
int.class, int.class });
Object result = addMethod.invoke(invokeOperation, new Object[] {
new Integer(first), new Integer(second) });
return result.toString();
} else if (oper.equals("-")) {
Method cutMethod = classType.getMethod("cut", new Class[] {
int.class, int.class });
Object result = cutMethod.invoke(invokeOperation, new Object[] {
new Integer(first), new Integer(second) });
return result.toString();
} else if (oper.equals("*")) {
Method rideMethod = classType.getMethod("ride", new Class[] {
int.class, int.class });
Object result = rideMethod.invoke(invokeOperation, new Object[] {
new Integer(first), new Integer(second) });
return result.toString();
} else if (oper.equals("/")) {
Method execMthod = classType.getMethod("Except", new Class[] {
int.class, int.class });
Object result = execMthod.invoke(invokeOperation, new Object[] {
new Integer(first), new Integer(second) });
return result.toString();
}
return "";
}
}
另一個小提醒:在純 Java 專案裡,我們習慣用 main 函式把結果印出來驗證;但在 Android 上直接這樣做容易出錯,改用 Log 或直接在介面上呈現會更穩妥。
自製 TabMenu 彈出選單:封裝成可重複使用的複合控件
用過 UC 瀏覽器 Android 版的人,大概都對它那個分頁式選單有印象。Android 原生的 OptionsMenu 有個先天限制:超過六項就被折進「更多」裡,能呈
Android 在地化實務:從 strings.xml 到語言切換
在地化的意義在地化不只是翻譯文字,也包括讓應用符合不同地區使用者的閱讀習慣。最常見的做法,是將畫面文字集中管理,並依語言提供不同資源。資源資料夾結構預設字串通常放在 re
Android SDK 線上更新鏡像伺服器大全與設定教學
中國科學院開源協會鏡像站位址:IPV4/IPV6: https://mirrors.opencas.cn 連接埠:80IPV4/IPV6: https://mirrors
Android 應用本地化實戰:讓 App 依地區顯示對應語言
Android 應用會在各種地區、各種裝置上被執行。為了讓 App 更貼近使用者,文字、數字、檔案等內容應該依裝置的語言環境調整呈現方式。 本章要說明的是如何依不同區域,