在许多类中共享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";
常数应为:
- public - 以便可以从任何地方访问
- static - 无需创建实例
- final - 因为它的常量不应该允许更改
- 根据Java命名约定,应该大写,以便于阅读并在Java文档中脱颖而出。
- public - so that it can be accessed from anywhere
- static - no need to create an instance
- final - since its constants shouldnt be allowed to change
- 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.