Replace Enum with Enumerated AnnotationsEdit Page History

Overview

“Magic Constants” or type annotations are regular old Java constants decorated in way that allows tools to recognize them as special values.Version 2.0 は、「マジック定数」または「タイプアノテーション」を意味します。 その構文は、他の Java 定数と変わりません。 その代わり、関連するすべての定数をリストする読みやすい名前の注釈を作成する必要があります。

このアノテーションは、戻り値またはメソッド パラメータを装飾し、受け入れられる値または期待される値について使用するツールにヒントを与えることができます。 その主な目的は、ソース コードを書いている間に、メソッド パラメーターおよび/またはメソッド戻り値の型安全性を強化することです。 Google は Android アプリ開発において enum の使用を推奨しておらず、開発者向けガイドラインで次のように述べています。 「enum は、静的定数の 2 倍以上のメモリを必要とすることがよくあります。 Enums は静的定数の 2 倍のメモリを必要とします。Android での enum の使用は厳密に避けるべきです」

IntDef

IntDef は、int 値のみを受け付けるパラメータがある場合に、整数の enum を置き換えるための方法です。 たとえば、次のようにフィードアイテムの型を記録したいとします。

public class ItemTypeDescriptor { public static final int TYPE_MUSIC = 0; public static final int TYPE_PHOTO = 1; public static final int TYPE_TEXT = 2; public final int itemType; public ItemTypeDescriptor(int itemType) { this.itemType = itemType; }}

今、コンストラクタに渡された型が有効であることを確認するための検証はありません。 IntDef を使用して、アノテーションを追加することにより、値が期待される値の 1 つであることを確認できます。

public class ItemTypeDescriptor { // ... type definitions // Describes when the annotation will be discarded @Retention(RetentionPolicy.SOURCE) // Enumerate valid values for this interface @IntDef({TYPE_MUSIC, TYPE_PHOTO, TYPE_TEXT}) // Create an interface for validating int types public @interface ItemTypeDef {} // Declare the constants public static final int TYPE_MUSIC = 0; public static final int TYPE_PHOTO = 1; public static final int TYPE_TEXT = 2; // Mark the argument as restricted to these enumerated types public ItemTypeDescriptor(@ItemTypeDef int itemType) { this.itemType = itemType; }}

最後の例と同じコンストラクタ呼び出しは、Android Studio でエラーが表示されます。 詳細については、公式の Android 注釈ガイドを参照してください。

StringDef

StringDef は同様に、明示的な文字列値のみを受け入れるべきパラメーターがある場合に、文字列 enum を置き換えるための方法です。 たとえば、次のような設定値を記録したいとします。

public class FilterColorDescriptor { public static final String FILTER_BLUE = "blue"; public static final String FILTER_RED = "red"; public static final String FILTER_GRAY = "gray"; public final String filterColor; public FilterColorDescriptor(String filterColor) { this.filterColor = filterColor; }}

今、コンストラクタに渡される型が有効であることを確認するための検証はありません。

public class FilterColorDescriptor { // ... type definitions // Describes when the annotation will be discarded @Retention(RetentionPolicy.SOURCE) // Enumerate valid values for this interface @StringDef({FILTER_BLUE, FILTER_RED, FILTER_GRAY}) // Create an interface for validating String types public @interface FilterColorDef {} // Declare the constants public static final String FILTER_BLUE = "blue"; public static final String FILTER_RED = "red"; public static final String FILTER_GRAY = "gray"; // Mark the argument as restricted to these enumerated types public FilterColorDescriptor(@FilterColorDef String filterColor) { this.filterColor = filterColor; }}

前の例と同じコンストラクタ呼び出しが Android Studio でエラーを表示するのは、期待される値がわかっているためです。 詳細については、Android の公式アノテーション ガイドを参照してください。