Java中定义常量方法及建议(Class/Interface)
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.
区别
上述两种方法对比,interface中定义常量方法生成的class文件比第一种方法的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://www.ibm.com/developerworks/cn/java/l-java-interface/index.html
https://www.jianshu.com/p/0affad4762ef
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异