Java中定義常量方法及建議(Class/Interface)

Class定義常量方法(推薦方法)

//final修飾符 public final class Constants { //私有構造方法 private Constants() {} public static final int ConstantA = 100; public static final int ConstantB = 100; ...... } 

採用「類.常量名」方法進行調用。須要私有化構造方法,避免建立該類的實例。同時不需讓其餘類繼承該類。html

若是多處須要訪問工具類中定義的常量,能夠經過靜態導入(static import)機制,避免用類名來修飾常量名。java

Interface定義常量方法

public interface Constants { int ConstantA = 100; int ConstantB = 100; ...... } 

在interface中聲明的字段,虛擬機在編譯時自動加上public static final修飾符。使用方法通常是「接口.常量名」。也能夠經過實現該接口,直接訪問常量名,即常量接口模式。工具

常量接口:即接口中不包含任何方法,只包含靜態的final域,每一個域都導出一個常量。使用這些常量的類實現這個接口,以免用類名來修飾常量名。this

常量接口模式是對接口的不良使用。具體參考以下:spa

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.code

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.orm

區別

上述兩種方法對比,interface中定義常量方法生成的class文件比第一種方法的class文件更小, 且代碼更簡潔, 效率更高.htm

可是在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://www.ibm.com/developerworks/cn/java/l-java-interface/index.html

https://www.jianshu.com/p/0affad4762ef

相關文章
相關標籤/搜索