我见过这样的例子:
public class MaxSeconds {
public static final int MAX_SECONDS = 25;
}
假设我可以有一个Constants类来包装常量,并将它们声明为静态final。我几乎不知道Java,我想知道这是否是创建常量的最佳方式。
我见过这样的例子:
public class MaxSeconds {
public static final int MAX_SECONDS = 25;
}
假设我可以有一个Constants类来包装常量,并将它们声明为静态final。我几乎不知道Java,我想知道这是否是创建常量的最佳方式。
当前回答
在单独的类中创建静态final常量可能会给您带来麻烦。Java编译器实际上会对此进行优化,并将常量的实际值放置到引用它的任何类中。
如果你稍后更改了Constants类,并且没有对引用该类的其他类进行严格的重新编译,那么你最终将使用新旧值的组合。
不要把它们看作常量,而应该把它们看作配置参数,并创建一个类来管理它们。让值是非final的,甚至可以考虑使用getter。将来,当您确定其中一些参数实际上应该由用户或管理员进行配置时,这将变得容易得多。
其他回答
这是正确的做法。
通常,常量不会保存在单独的“常量”类中,因为它们是不可发现的。如果常量与当前类相关,那么保留它们有助于下一个开发人员。
只是要避免使用接口:
public interface MyConstants {
String CONSTANT_ONE = "foo";
}
public class NeddsConstant implements MyConstants {
}
这很诱人,但违反了封装,并且模糊了类定义的区别。
一个好的面向对象设计不应该需要很多公开可用的常量。大多数常量都应该封装在需要它们完成工作的类中。
有一定的观点来回答这个问题。首先,java中的常量通常被声明为public、static和final。原因如下:
public, so that they are accessible from everywhere
static, so that they can be accessed without any instance. Since they are constants it
makes little sense to duplicate them for every object.
final, since they should not be allowed to change
我永远不会为CONSTANTS访问器/对象使用接口,因为接口通常是需要实现的。这看起来是不是很有趣:
String myConstant = IMyInterface.CONSTANTX;
相反,我会在一些不同的方法中进行选择,基于一些小的权衡,所以这取决于你需要什么:
1. Use a regular enum with a default/private constructor. Most people would define
constants this way, IMHO.
- drawback: cannot effectively Javadoc each constant member
- advantage: var members are implicitly public, static, and final
- advantage: type-safe
- provides "a limited constructor" in a special way that only takes args which match
predefined 'public static final' keys, thus limiting what you can pass to the
constructor
2. Use a altered enum WITHOUT a constructor, having all variables defined with
prefixed 'public static final' .
- looks funny just having a floating semi-colon in the code
- advantage: you can JavaDoc each variable with an explanation
- drawback: you still have to put explicit 'public static final' before each variable
- drawback: not type-safe
- no 'limited constructor'
3. Use a Class with a private constructor:
- advantage: you can JavaDoc each variable with an explanation
- drawback: you have to put explicit 'public static final' before each variable
- you have the option of having a constructor to create an instance
of the class if you want to provide additional functions related
to your constants
(or just keep the constructor private)
- drawback: not type-safe
4. Using interface:
- advantage: you can JavaDoc each variable with an explanation
- advantage: var members are implicitly 'public static final'
- you are able to define default interface methods if you want to provide additional
functions related to your constants (only if you implement the interface)
- drawback: not type-safe
静态final是我的偏好,我只使用enum如果项目确实是可枚举的。