在Java中定义常量字符串?

css*_*sss 59 java string

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

在CI中可以在我的代码顶部定义这样的字符串:

#define WELCOME_MESSAGE "Hello, welcome to the server"
#define WAIT_MESSAGE "Please wait 5 seconds"
#define EXIT_MESSAGE "Bye!"
Run Code Online (Sandbox Code Playgroud)

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

der*_*ann 116

通常,您会将其定义为类的顶部:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
Run Code Online (Sandbox Code Playgroud)

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

  • 不,它应该仍然是"静态的".每次实例化类型时,将其设置为私有和非静态仍会创建字符串的新副本.请参见http://stackoverflow.com/q/1415955/247763 (7认同)
  • 我一直想知道,如果你将常量定义为'private',是不是不必将常量设置为'static'? (2认同)

Ern*_*ill 12

它看起来像这样:

public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
Run Code Online (Sandbox Code Playgroud)

如果常量只在一个类中使用,那么你需要制作它们private而不是public.


ReP*_*PRO 5

public static final String YOUR_STRING_CONSTANT = "";
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以使用

 public static final String HELLO = "hello";
Run Code Online (Sandbox Code Playgroud)

如果你有很多字符串常量,你可以使用外部属性文件/简单的“常量持有者”类


V_S*_*ngh 5

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


Pri*_*jee 5

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

因此,如果我们创建常量,static它就不会这样做并且会节省内存

随着final我们可以把这些变量不变。

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

private static final String YOUR_CONSTANT = "Some Value"; 
Run Code Online (Sandbox Code Playgroud)

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

  • 这里使用了字符串池,因为您不使用“new”关键字来创建字符串。因此,即使您不对字符串使用静态,它也会使用字符串池中已经创建的引用。查看更多:http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal (3认同)