在许多类中共享Java中的常量字符串?

在许多类中共享Java中的常量字符串?

问题描述:

我想在一个地方拥有Java常量字符串,并在整个项目中使用它们(许多类)。

I'd like to have Java constant strings at one place and use them across whole project (many classes).

推荐的实现方法是什么?

What is the recommended way of achieveing this?

public static final String CONSTANT_STRING="CONSTANT_STRING";

常数应为:


  1. public - 以便可以从任何地方访问

  2. static - 无需创建实例

  3. final - 因为它的常量不应该允许更改

  4. 根据Java命名约定,应该大写,以便于阅读并在Java文档中脱颖而出。

  1. public - so that it can be accessed from anywhere
  2. static - no need to create an instance
  3. final - since its constants shouldnt be allowed to change
  4. As per Java naming convention should be capitalized so that easy to read and stands out in Java documentation.

有些情况下接口仅用于保持常量,虽然我没有看到任何理由这样做,并且创建一个接口来保持常量也被认为是一种不好的做法,另一种方法是将它保留在更有意义的类中。

There are instances where interfaces are used just to keep constants though I don't see any reason to do that and is also considered a bad practice to create an interface to hold constants, another approach is to keep it in the class where it makes more sense.

例如

JFrame EXIT_ON_CLOSE 包含,任何子类 JFrame 的类都可以访问它,它也是有意义的是保留在 JFrame 而不是 JComponent ,因为并非所有组件都有一个可以关闭的选项。

JFrame has EXIT_ON_CLOSE contant, any class which subclasses JFrame will have access to it and it also makes sense to keep in JFrame and not in JComponent as not all components will have an option to be closed.