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

Android 自訂註解:概念、元註解與兩個實戰案例

編輯:關於 Android 程式設計

前言

註解的使用頻率一直很高。ButterKnife 這類注入框架、ActiveAndroid 這類資料庫框架,都是靠註解把開發效率拉起來的。因此理解註解的運作方式並能熟練使用,對 Android 開發者來說相當重要。本文分兩部分:第一部分梳理註解與元註解的概念;第二部分用兩個小範例,示範如何以「註解 + 反射」完成網路請求封裝與資料庫操作。

什麼是註解

註解是一種元資料,可以附加在 Java 程式碼上。類別、方法、變數、參數、套件都能被註解,而註解本身對被標註的程式碼沒有直接影響。

元註解

Java 內建的註解有 Override、Deprecated、SuppressWarnings 等。看看 Override 的原始碼:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override { }

可以發現 Override 上面還有兩個註解——這就是元註解。元註解是用來「定義註解」的註解,負責描述一個註解的作用範圍、可以標註在哪些元素上等等。共有四種:@Retention、@Target、@Inherited、@Documented。

@Target

@Target 說明該註解可以修飾的對象範圍,也就是它能用在哪些地方。取值(ElementType)有:

CONSTRUCTOR:建構子
FIELD:欄位
LOCAL_VARIABLE:區域變數
METHOD:方法
PACKAGE:套件
PARAMETER:參數
TYPE:類別、介面(含註解型別)或 enum 宣告

@Retention

@Retention 定義註解被保留的時間長短:有些註解只存在於原始碼中,編譯時就被丟棄;有些會被寫進 class 檔;寫進 class 檔的那些,也可能被虛擬機忽略,或在類別載入時才被讀取。取值(RetentionPolicy)有:

SOURCE:原始檔中有效
CLASS:class 檔中有效
RUNTIME:執行階段有效

@Documented

@Documented 用來表示該註解應被視為被標註項目的公開 API,因此可以被 javadoc 這類工具納入文件。它是一個標記註解,沒有任何成員。

@Inherited

@Inherited 也是標記註解,用來宣告某個被標註的型別會被繼承。如果一個使用 @Inherited 修飾的註解型別被用在某個類別上,那麼該類別的子類別也會帶有這個註解。

要注意的是:@Inherited 只在「類別繼承類別」時生效,類別不會從它實作的介面繼承註解,方法也不會從它覆寫的方法繼承註解。此外,當 @Inherited 註解的 Retention 為 RUNTIME 時,反射 API 會強化這種繼承性——查詢時會一路往上檢查父類別,直到找到該註解或抵達繼承結構頂端。

其中 @Retention 決定了保留策略,也就直接決定了要用什麼方式解析。SOURCE 級別的註解只是拿來做標記,例如 Override、SuppressWarnings;真正實用來承載資訊的是 CLASS(編譯期處理)與 RUNTIME(執行期反射)兩種。

自訂註解

使用 @interface 自訂註解時,會自動繼承 java.lang.annotation.Annotation 介面,其餘細節交給編譯器處理。定義註解時不能繼承其他註解或介面。@interface 用來宣告註解,其中的每個方法實際上就是一個設定參數:方法名稱即參數名稱,回傳型別即參數型別(只能是基本型別、Class、String、enum),並可用 default 指定預設值。

定義格式:

public @interface 註解名 { 定義體 }

參數支援的型別:

所有基本型別(int、float、boolean、byte、double、char、long、short)、String、Class、enum、Annotation,以及以上各型的陣列。

範例一:用註解封裝網路請求參數

發請求時總要提供介面位址、請求參數等資訊。下面示範如何用反射與註解把這段拼裝工作自動化。

先定義請求端口:

package demo.src.demo.request.host;

public enum Host {
    Host_1("https://L1"),
    Host_2("https://T2"),
    Host_3("https://R3");

    private String host;

    Host(String host) { this.host = host; }

    public String getHost() { return host; }
}

接著定義兩個註解,一個描述鍵值對的 key,一個描述請求的位址與相關設定:

package demo.src.demo.request.params;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface RequestParamsKey {
    String key();
}
package demo.src.demo.request.params;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import demo.src.demo.request.host.Host;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface RequestParamsUrl {
    String url();                        // 介面位址
    Host host() default Host.Host_1;     // 端口
    boolean isCache() default false;     // 是否緩存
}

然後寫一個解析器,用反射讀出標註資訊並拼成完整的請求路徑:

package demo.src.demo.request;

import java.lang.reflect.Field;
import demo.src.demo.request.params.RequestParamsKey;
import demo.src.demo.request.params.RequestParamsUrl;

/**
 * 拼接請求參數
 */
public class RequestParam {

    private RequestParam() { }

    /** 取得 request 參數 */
    public static String getParam(Class<?> _clazz, Object _object) {
        Class<?> clazz = _clazz;
        Field[] fields = clazz.getDeclaredFields();
        try {
            return requestParam(fields, clazz, _object);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 取得請求路徑 */
    private static String requestParam(Field[] fields, Class<?> clazz, Object _object)
            throws IllegalArgumentException, IllegalAccessException {
        StringBuilder request = new StringBuilder();

        RequestParamsUrl requestParamsUrl = clazz.getAnnotation(RequestParamsUrl.class);
        if (requestParamsUrl != null) {
            String url     = requestParamsUrl.url();
            boolean isCache = requestParamsUrl.isCache();
            String host    = requestParamsUrl.host().getHost();
            request.append(host);
            request.append(url);
            request.append("?");
            System.out.println("請求端口:" + host);
            System.out.println("請求地址:" + url);
            System.out.println("是否緩存:" + isCache);
        }

        for (Field field : fields) {
            RequestParamsKey requestParamsKey = field.getAnnotation(RequestParamsKey.class);
            if (requestParamsKey != null) {
                String key   = requestParamsKey.key();
                String Value = (String) field.get(_object);
                request.append(key).append("=").append(Value).append("&");
            }
        }
        request.deleteCharAt(request.length() - 1);
        System.out.println("請求路徑:" + request.toString());
        return request.toString();
    }
}

最後定義具體的請求物件,用註解把位址與參數 key 標上去就好:

package demo.src.demo.reqBody;

import demo.src.demo.request.host.Host;
import demo.src.demo.request.params.RequestParamsKey;
import demo.src.demo.request.params.RequestParamsUrl;

@RequestParamsUrl(url = "getLocation.php", isCache = true, host = Host.Host_2)
public class LocationReq {
    @RequestParamsKey(key = "lat_key") public String lat;
    @RequestParamsKey(key = "lan_key") public String lan;
}
package demo.src.demo;

import demo.src.demo.reqBody.LocationReq;
import demo.src.demo.request.RequestParam;

public class demo {

    public LocationReq mLocation;

    public static void main(String[] args) throws ClassNotFoundException {
        demo demo = new demo();
        demo.cofig();
        demo.getRequest();
    }

    /** 設定請求參數 */
    private void cofig() {
        mLocation = new LocationReq();
        mLocation.lan = "123.09";
        mLocation.lat = "232.34";
    }

    /** 取得請求路徑 */
    private void getRequest() {
        System.out.println(RequestParam.getParam(mLocation.getClass(), mLocation));
    }
}

輸出結果:

請求端口:https://T2
請求地址:getLocation.php
是否緩存:true
請求路徑:https://T2getLocation.php?lat_key=232.34&lan_key=123.09

新增一個介面時,只要多寫一個帶註解的類別,拼參數的樣板程式碼完全不用動——這就是註解帶來的價值。

範例二:用註解定義資料庫表結構

接著把同樣的思路搬到資料庫上:用註解描述表名、欄位名,讓建表語句自動產生。

SqliteHelper 負責建立與更新資料庫:

package com.example.dbannotion.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 資料庫
 */
public class SqliteHelper extends SQLiteOpenHelper {

    private String createTable;
    private String tableName;

    public SqliteHelper(Context context, String name, CursorFactory factory, int version,
                         String createTable, String tableName) {
        super(context, name, factory, version);
        this.createTable = createTable;
        this.tableName   = tableName;
    }

    /** 建立表 */
    @Override
    public void onCreate(SQLiteDatabase db) {
        if (createTable != "") {
            db.execSQL(createTable);
        }
    }

    /** 更新表 */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + tableName);
        onCreate(db);
    }

    /** 更新列 */
    public void updateColumn(SQLiteDatabase db, String oldColumn, String newColumn, String typeColumn) {
        try {
            db.execSQL("ALTER TABLE " + tableName + " CHANGE " + oldColumn + " " + newColumn + " " + typeColumn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

兩個註解分別對應欄位與表:

package com.example.dbannotion.db.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ColumDB {
    String column();
}
package com.example.dbannotion.db.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface TableDB {
    String table();                       // 表名
    String dbName() default "demoDb.db";  // 資料庫名稱
    int version() default 1;              // 版本號
}

AbstractDB 是整個結構的核心,用反射把註解翻譯成建表語句與 ContentValues:

package com.example.dbannotion.db;

import java.lang.reflect.Field;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.example.dbannotion.db.annotation.ColumDB;
import com.example.dbannotion.db.annotation.TableDB;

public abstract class AbstractDB {

    public static final String TAG = "AbstractDB";

    private SQLiteDatabase db;
    private SqliteHelper dbHelper;

    private int version;        // 版本
    private String dbName;      // 資料庫名稱
    private String tableName;   // 表名
    private StringBuilder createBuilder;  // 建表語句
    private ContentValues contentValues = new ContentValues();  // 待插入的資料
    private boolean isColums;   // 是否存在資料
    private ArrayList<String> clumsList = new ArrayList<String>();

    /** 開啟資料庫 */
    public AbstractDB open(Context _context, Class<?> _clazz, Object _object) {
        if (paramsDB(_clazz, _object)) {
            dbHelper = new SqliteHelper(_context, dbName, null, version, createBuilder.toString(), tableName);
            db = dbHelper.getWritableDatabase();
            Log.e(TAG, "-------------資料庫打開成功!----------");
        } else {
            Log.e(TAG, "-------------資料庫打開失敗!----------");
        }
        return this;
    }

    /** 開啟資料庫時是否直接插入 */
    public AbstractDB isInsert(boolean isInsert) {
        if (isInsert && isColums) {
            insert();
        }
        return this;
    }

    /** 建立並檢查資料庫,回傳 false 代表失敗 */
    public boolean paramsDB(Class<?> _clazz, Object _object) {
        isColums = false;
        contentValues.clear();
        clumsList.clear();
        createBuilder = new StringBuilder();
        Class<?> clazz = _clazz;
        Field[] fields = clazz.getDeclaredFields();
        createBuilder.append("CREATE TABLE IF NOT EXISTS ");

        /* 表名 */
        TableDB tDb = _clazz.getAnnotation(TableDB.class);
        if (tDb != null) {
            dbName    = tDb.dbName();
            tableName = tDb.table();
            version   = tDb.version();
            createBuilder.append(tableName);
            createBuilder.append("(");
        } else {
            return false;
        }

        /* 欄位 */
        for (Field field : fields) {
            ColumDB requestParamsKey = field.getAnnotation(ColumDB.class);
            if (requestParamsKey != null) {
                String key = requestParamsKey.column();
                String value;
                try {
                    value = (String) field.get(_object);
                    clumsList.add(key);
                    if (!value.isEmpty()) {
                        contentValues.put(key, value);
                    }
                    createBuilder.append(key);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
                createBuilder.append(" varchar,");
                isColums = true;
            }
        }

        if (!isColums) {
            return false;
        }
        createBuilder.deleteCharAt(createBuilder.length() - 1);
        createBuilder.append(")");
        return true;
    }

    public AbstractDB insert() {
        if (contentValues != null) {
            db.insert(tableName, null, contentValues);
            Log.e(TAG, "-------------資料添加成功!----------");
        } else {
            Log.e(TAG, "-------------資料添加失敗!----------");
        }
        return this;
    }

    /** 取得資料 */
    public String getDate() {
        StringBuilder dateBuilder = new StringBuilder();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from " + tableName, null);
        while (cursor.moveToNext()) {
            if (clumsList != null) {
                for (int i = 0, length = clumsList.size(); i < length; i++) {
                    String name = cursor.getString(cursor.getColumnIndex(clumsList.get(i)));
                    dateBuilder.append(clumsList.get(i)).append("=").append(name).append(",");
                }
                dateBuilder.append("\n");
            }
        }
        cursor.close();
        if (dateBuilder.length() > 1) {
            dateBuilder.deleteCharAt(dateBuilder.length() - 1);
            return dateBuilder.toString();
        } else {
            Log.e(TAG, "-------------無數據解析!----------");
            return "";
        }
    }

    public void Close() {
        db.close();
        dbHelper.close();
    }
}

於是建表這件事,就變成寫一個帶註解的類別:

package com.example.dbannotion.table;

import com.example.dbannotion.db.AbstractDB;
import com.example.dbannotion.db.annotation.ColumDB;
import com.example.dbannotion.db.annotation.TableDB;

@TableDB(table = "student", dbName = "demo.db", version = 1)
public class Student extends AbstractDB {
    @ColumDB(column = "name") public String name;
    @ColumDB(column = "age")  public String age;
    @ColumDB(column = "sex")  public String sex;
}

這段宣告的含義是:建立 demo.db 資料庫,表名 student,版本號 1,包含 name、age、sex 三個欄位。

使用端就顯得非常乾淨:

package com.example.dbannotion;

import com.example.dbannotion.table.Student;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    private Student student;
    public TextView tv_show;
    public Button btn_get;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initDate();
        initView();
        initEvent();
    }

    private void initView() {
        tv_show = (TextView) findViewById(R.id.tv_show);
        btn_get = (Button) findViewById(R.id.btn_get);
    }

    private void initEvent() {
        btn_get.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        tv_show.setText(student.getDate());
                    }
                });
            }
        });
    }

    private void initDate() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    student = new Student();
                    student.age  = i + "";
                    student.name = "name-" + i;
                    student.sex  = (i % 2 == 0) ? "男" : "女";
                    student.open(MainActivity.this, student.getClass(), student).isInsert(true);
                }
            }
        }).start();
    }
}

執行結果:

結語

兩個範例只是想拋磚引玉。 thực 際專案裡,註解框架的價值在於把「每次都要重寫的樣板」收斂成一次性的宣告:新增介面或資料表時只寫註解,解析邏輯留在框架裡。需要提醒的是,反射解析有效能成本,也不要在註解裡塞入過多業務判斷——註解適合描述結構,不適合承載複雜邏輯。掌握這個界線,再回頭看 ButterKnife、Room 這類框架的原始碼,就會發現它們做的其實是同一件事。

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