我见过这样的例子:

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

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


当前回答

您可能犯的第一个错误是创建一个全局可访问的类,类名为泛型名称,如Constants。这只会充斥着垃圾,您将无法确定系统的哪个部分使用了这些常量。

相反,常量应该放到“拥有”它们的类中。有一个叫TIMEOUT的常量吗?它应该放到Communications()或Connection()类中。MAX_BAD_LOGINS_PER_HOUR吗?进入User()。诸如此类。

当“常量”可以在运行时定义,但用户不容易更改时,另一种可能的用法是Java .properties文件。你可以把它们打包到你的.jar文件中,并使用Class resourceLoader引用它们。

其他回答

那么枚举呢?

更进一步,您可以将全局使用的常量放在接口中,这样它们就可以在系统范围内使用。如。

public interface MyGlobalConstants {
    public static final int TIMEOUT_IN_SECS = 25;
}

但是不要执行它。只需在代码中通过完全限定类名直接引用它们。

我强烈建议不要只使用一个常量类。这在当时看起来是一个好主意,但是当开发人员拒绝记录常量,并且类增长到包含500个以上彼此完全不相关的常量(与应用程序的完全不同方面相关)时,通常会导致常量文件完全不可读。而不是:

If you have access to Java 5+, use enums to define your specific constants for an application area. All parts of the application area should refer to enums, not constant values, for these constants. You may declare an enum similar to how you declare a class. Enums are perhaps the most (and, arguably, only) useful feature of Java 5+. If you have constants that are only valid to a particular class or one of its subclasses, declare them as either protected or public and place them on the top class in the hierarchy. This way, the subclasses can access these constant values (and if other classes access them via public, the constants aren't only valid to a particular class...which means that the external classes using this constant may be too tightly coupled to the class containing the constant) If you have an interface with behavior defined, but returned values or argument values should be particular, it is perfectly acceptible to define constants on that interface so that other implementors will have access to them. However, avoid creating an interface just to hold constants: it can become just as bad as a class created just to hold constants.

只是要避免使用接口:

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

public class NeddsConstant implements MyConstants {

}

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

我更喜欢使用getter而不是常量。这些getter可能返回常量值,例如public int getMaxConnections() {return 10;},但任何需要常量的东西都将通过getter。

一个好处是,如果您的程序超出了常量的使用范围——您发现它需要可配置——您可以更改getter返回常量的方式。

另一个好处是,为了修改常量,你不必重新编译所有使用它的东西。当引用静态final字段时,该常量的值将被编译到引用它的任何字节码中。