Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

用 Java 反射機制打造 Android 計算器:從原理到實作

編輯:Android 開發實例

先搞懂:Java 反射機制到底是什麼

所謂反射(Reflection),指的是程式在執行階段仍能「看清自己」的能力:對於任意一個類別,我們可以取得它的全部欄位與方法;對於任意一個物件,我們也可以動態地呼叫它身上的方法。這種在執行期才決定要操作誰、要呼叫什麼的機制,就是 Java 反射。

反射主要帶來幾種能力:在執行期判斷某個物件屬於哪個類別、動態建立任意類別的物件、讀取該類別的成員變數與方法、呼叫任意物件的方法,以及產生動態代理。

「動態」這個詞其實很滑溜

我們常把動態綁定、動態連結、動態載入掛在嘴邊,但「動態」從來沒有一個放諸四海皆準的嚴格定義,工程師社群往往各說各話。比較被接受的說法是:如果一個語言允許在執行時改變程式結構或變數型別,它就是動態語言。用這個標準看,Perl、Python、Ruby 算動態語言,而 C++、Java、C# 不算。

有趣的是,Java 雖然被歸在「非動態」那一側,卻擁有一個極為亮眼的動態機制——Reflection。這個字本意是反射、倒影,用在 Java 身上,意思是我們可以在執行期載入、探查並使用那些在編譯時完全未知的類別。也就是說,程式可以載入一個名稱到執行時才知道的 class,摸清它的完整結構,建立物件實體、為欄位設值、或呼叫它的方法。這種「看透 class」的能力,也被稱為 introspection(內省)。Reflection 與 introspection 這兩個術語經常被並肩提起。

為什麼 Android 開發會需要反射

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 或直接在介面上呈現會更穩妥。

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