我见过这样的例子:

public class MaxSeconds {
   public static final int MAX_SECONDS = 25;
}

假设我可以有一个Constants类来包装常量,并将它们声明为静态final。我几乎不知道Java,我想知道这是否是创建常量的最佳方式。


当前回答

总之,以秒为单位的timeout值应该是一个配置设置(从属性文件中读取或像Spring中那样通过注入),而不是一个常量。

其他回答

那么枚举呢?

只是要避免使用接口:

public interface MyConstants {
    String CONSTANT_ONE = "foo";
}

public class NeddsConstant implements MyConstants {

}

这很诱人,但违反了封装,并且模糊了类定义的区别。

这是正确的做法。

通常,常量不会保存在单独的“常量”类中,因为它们是不可发现的。如果常量与当前类相关,那么保留它们有助于下一个开发人员。

I use static final to declare constants and go with the ALL_CAPS naming notation. I have seen quite a few real life instances where all constants are bunched together into an interface. A few posts have rightly called that a bad practice, primarily because that's not what an interface is for. An interface should enforce a contract and should not be a place to put unrelated constants in. Putting it together into a class that cannot be instantiated (through a private constructor) too is fine if the constant semantics don't belong to a specific class(es). I always put a constant in the class that it's most related to, because that makes sense and is also easily maintainable.

枚举是表示一组值的好选择,但是如果您要存储强调绝对值的独立常量(例如。TIMEOUT = 100 ms)你可以直接使用静态的final方法。

我这样做的方法之一是通过创建一个具有常量值的“全局”类,并在需要访问常量的类中进行静态导入。