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

Android 反射機制實戰:用 Class.forName 動態呼叫方法做計算機

編輯:關於 Android 程式設計

本文以一個加減乘除計算機為例,示範如何在 Android 中用 Java 反射機制動態取得類別、建立實例並呼叫方法。

先搞懂什麼是反射

Java 反射機制的定義是:在運行狀態中,對於任意一個類別,都能得知它的所有屬性與方法;對於任意一個物件,都能呼叫它的任何一個方法。這種「動態取得資訊並動態呼叫方法」的能力,就稱為反射。

反射主要提供以下功能:

  • 在執行期判斷任意物件所屬的類別
  • 在執行期建構任意類別的物件
  • 在執行期判斷任意類別的成員變數與方法
  • 在執行期呼叫任意物件的方法
  • 產生動態代理

談到「動態語言」,社群大致認同的定義是:「程式運行時允許改變程式結構或變數類型」。以此標準,Perl、Python、Ruby 是動態語言,C++、Java、C# 不是。但 Java 雖不屬於動態語言,卻有一個非常突出的動態相關機制——Reflection。這個字本意是「反射、映象、倒影」,用在 Java 身上指的是我們可以在執行期載入、探知、使用編譯期間完全未知的類別。

換句話說,Java 程式可以載入一個執行期才知道名稱的類別,取得它的完整結構,並生成物件實體、對其欄位設值、或呼叫其方法。這種「看透類別」的能力被稱為 introspection(內省)。Reflection 與 introspection 是常被並提的兩個術語。

在 Android 中,有不少類別是被封閉的——例如 ServiceManager、藍牙模組中有大量類別並未對外開放。要使用它們,就得靠反射把類別轉成物件來操作。Android 應用本身以 Java 為基礎,自然也具備這項能力。

一、定義被呼叫的類別

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"
        android:inputType="number"></EditText>

    <EditText android:id="@+id/EditText02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="number"></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 android:text="-" android:id="@+id/Button02"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:text="*" android:id="@+id/Button03"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:text="/" android:id="@+id/Button04"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
        <Button android:text="=" android:id="@+id/Button05"
            android:layout_width="wrap_content" android:layout_height="wrap_content"/>
    </LinearLayout>
</LinearLayout>

三、反射的四個基本動作

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 });

參數一是我們要找的方法名稱,參數二是該方法的參數型別陣列。這裡如果只寫方法名稱而漏掉參數型別,會拋 NoSuchMethodException——因為 Java 支援方法多載,必須靠參數清單才能唯一確定一個方法。

4. 呼叫方法並取得回傳值。

Object result = addMethod.invoke(invokeOperation,
        new Object[]{ new Integer(first), new Integer(second) });

第一個參數是「要在哪個物件上呼叫」,後面是實際傳入的參數。

四、完整程式碼

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 (Exception 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");
        // 若類別就在專案內,也可以寫成:Class<?> classType = operationClass.class;

        // 建立實例
        Object invokeOperation = classType.newInstance();

        if (oper.equals("+")) {
            Method m = classType.getMethod("add", new Class[]{ int.class, int.class });
            return m.invoke(invokeOperation, new Object[]{ first, second }).toString();
        } else if (oper.equals("-")) {
            Method m = classType.getMethod("cut", new Class[]{ int.class, int.class });
            return m.invoke(invokeOperation, new Object[]{ first, second }).toString();
        } else if (oper.equals("*")) {
            Method m = classType.getMethod("ride", new Class[]{ int.class, int.class });
            return m.invoke(invokeOperation, new Object[]{ first, second }).toString();
        } else if (oper.equals("/")) {
            Method m = classType.getMethod("Except", new Class[]{ int.class, int.class });
            return m.invoke(invokeOperation, new Object[]{ first, second }).toString();
        }
        return "";
    }
}

實務上關於反射的幾點提醒

  • 反射會耗系統資源,非必要不使用。行動裝置對資源的要求相對嚴苛,尤其在列表項、動畫等每秒執行多次的路徑上,反射的效能差距很明顯。此外 Android 的 newInstance() 在早期版本上有已知效能問題。
  • 類別名稱寫死在字串裡,編譯器無法檢查。重構時改名不會有錯誤提示,只會在執行期丟 ClassNotFoundException。若只是為了「動態」而犧牲型別安全,通常不划算。
  • ProGuard/R8 會把反射用到的類別與方法移除或改名。必須在 proguard-rules.pro 加上 -keep 規則,否則正式簽名稱的 apk 會 crash。
  • Android 9(API 28)起限制非 SDK 介面呼叫。反射呼叫隱藏 API 會被攔下並印出警告,最高限制的類別會直接拋例外。這使得「用反射破解系統 API」的舊套路越來越行不通。
  • 更現代的替代方案。若目的是「依字串動態決定行為」,用 enum 或 Map<String, Interface> 查表會比反射更快也更安全;若要做依賴注入,直接用 Dagger/Hilt 會省去大量反射樣板。

補充一點:Java 中可以用 main 函式直接執行與除錯,但在 Android 裡沒有獨立的 main 進入點,直接照那種方式呼叫會出錯,需要透過 Activity 或測試框架來驅動。

以上就是反射機制的基本用法示範。理解它的原理與成本之後,才能在「真的需要」與「其實有更好的方法」之間做出正確判斷。

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