Class定義常量方法(推薦方法)
//final修飾符
public final class Constants {
//私有構(gòu)造方法
private Constants() {}
public static final int ConstantA = 100;
public static final int ConstantB = 100;
......
}
采用“類.常量名”方法進(jìn)行調(diào)用。需要私有化構(gòu)造方法,避免創(chuàng)建該類的實(shí)例。同時(shí)不需讓其他類繼承該類。
如果多處需要訪問工具類中定義的常量,可以通過靜態(tài)導(dǎo)入(static import)機(jī)制,避免用類名來修飾常量名。
Interface定義常量方法
public interface Constants {
int ConstantA = 100;
int ConstantB = 100;
......
}
在interface中聲明的字段,虛擬機(jī)在編譯時(shí)自動加上public static final修飾符。使用方法一般是“接口.常量名”。也可以通過實(shí)現(xiàn)該接口,直接訪問常量名,即常量接口模式。
常量接口:即接口中不包含任何方法,只包含靜態(tài)的final域,每個(gè)域都導(dǎo)出一個(gè)常量。使用這些常量的類實(shí)現(xiàn)這個(gè)接口,以避免用類名來修飾常量名。
常量接口模式是對接口的不良使用。具體參考如下:
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.
區(qū)別
上述兩種方法對比,interface中定義常量方法生成的class文件比第一種方法的class文件更小, 且代碼更簡潔, 效率更高.
但是在java中會產(chǎn)生問題,主要是java的動態(tài)性,java中一些字段的引用可以在運(yùn)行期動態(tài)進(jìn)行。某些場景下,部分內(nèi)容改變可只進(jìn)行部分編譯。具體例子參考文檔Java Interface 是常量存放的最佳地點(diǎn)嗎?
該文推薦使用Class定義常量,但采用private修飾符,通過get方法獲取常量。這種方案可以保證java的動態(tài)性。
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-constants
Java Interface 是常量存放的最佳地點(diǎn)嗎?
關(guān)于Java常量定義的一點(diǎn)思考