在 Java 中定义常量字符串?

我有一个常量字符串列表,需要在 Java 程序中的不同时间显示。

在 C 语言中,我可以像这样在代码顶部定义字符串:

#define WELCOME_MESSAGE "Hello, welcome to the server"
#define WAIT_MESSAGE "Please wait 5 seconds"
#define EXIT_MESSAGE "Bye!"

我想知道在 Java 中做这种事情的标准方法是什么?

206884 次浏览

通常情况下,你会把它定义为类的顶端:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server";

当然,根据使用此常量的位置使用适当的成员可见性(public/private/protected)。

它看起来像这样:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server";

如果这些常量仅用于单个类,那么应该将它们设置为 private而不是 public

public static final String YOUR_STRING_CONSTANT = "";

你可以用

 public static final String HELLO = "hello";

如果有许多字符串常量,可以使用外部属性 file/simple “固定持有人”类

简单地使用

final String WELCOME_MESSAGE = "Hello, welcome to the server";

本指令的主要部分是‘ final’关键字。

或者行业中的另一个典型标准是拥有一个 Constants.java 命名的类文件,其中包含所有在项目中使用的常量。

我们通常将常数声明为 static。这是因为 Java 在每次实例化类的对象时都会创建非静态变量的副本。

因此,如果我们使常数 static,它不会这样做和 可以节省记忆

使用 final我们可以使变量为常数。

因此,定义常量变量的最佳实践如下:

private static final String YOUR_CONSTANT = "Some Value";

访问修饰符可以是 private/public,这取决于业务逻辑。