Javaで定数を定義する方法および推奨事項(Class/Interface)

2468 ワード

Class定数メソッドの定義(推奨メソッド)
//final   
public final class Constants {
    //      
    private Constants() {}

    public static final int ConstantA = 100;
    public static final int ConstantB = 100;
    ......
}

「クラス.定数名」メソッドを使用して呼び出します.クラスのインスタンスを作成しないように、プライベート構造メソッドが必要です.他のクラスにクラスを継承させる必要はありません.
ツールクラスで定義された定数にアクセスする必要がある場合は、クラス名で定数名を修飾することを避けるために、静的インポート(static import)メカニズムを使用します.
Interface定義定数メソッド
public interface Constants {
    int ConstantA = 100;
    int ConstantB = 100;
    ......
}

Interfaceで宣言されたフィールドには、仮想マシンがコンパイル時にpublic static final修飾子を自動的に追加します.使用方法は「インタフェース.定数名」が一般的です.このインタフェースを実装することによって、定数名、すなわち定数インタフェースモードに直接アクセスすることもできる.
定数インタフェース:インタフェースにはメソッドが含まれず、静的finalドメインのみが含まれ、各ドメインに定数がエクスポートされます.このインタフェースは、クラス名で定数名を修飾しないように、これらの定数のクラスを使用して実装されます.
定数インタフェースモードはインタフェースの不良使用です.具体的な参考は以下の通りです.
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
There are several constant interfaces in the java platform libraries, such as java.io.ObjectStreamConstants. These interfaces should be regarded as anomalies and should not be emulated.
区別する
上記の2つの方法と比較する、interfaceで定義定数の方法で生成されるclassファイルは、第1の方法のclassファイルよりも小さく、コードがより簡潔で、効率が高い.
しかしjavaでは問題が発生し、主にjavaのダイナミック性であり、javaの一部のフィールドの参照は実行期間中にダイナミックに行うことができます.一部のシーンでは、一部のコンテンツの変更は部分的なコンパイルのみを行うことができます.具体例参考ドキュメントJava Interfaceは定数保存に最適な場所ですか?
この文書ではClassを使用して定数を定義することを推奨しますが、private修飾子を使用してgetメソッドで定数を取得します.このスキームはjavaのダイナミック性を保証することができる.
public class A{
    private static final String name = "bright";
    public static String getName(){
        return name;
    }
}

参照ドキュメント:https://stackoverflow.com/questions/2659593/what-is-the-use-of-interface-constantsJava Interfaceは定数保存に最適な場所ですか?Java定数定義について考える