我见过这样的例子:
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,我想知道这是否是创建常量的最佳方式。
当前回答
我更喜欢使用getter而不是常量。这些getter可能返回常量值,例如public int getMaxConnections() {return 10;},但任何需要常量的东西都将通过getter。
一个好处是,如果您的程序超出了常量的使用范围——您发现它需要可配置——您可以更改getter返回常量的方式。
另一个好处是,为了修改常量,你不必重新编译所有使用它的东西。当引用静态final字段时,该常量的值将被编译到引用它的任何字节码中。
其他回答
只是要避免使用接口:
public interface MyConstants {
String CONSTANT_ONE = "foo";
}
public class NeddsConstant implements MyConstants {
}
这很诱人,但违反了封装,并且模糊了类定义的区别。
那么枚举呢?
根据上面的评论,我认为这是一个很好的方法,将老式的全局常量类(具有公共静态final变量)更改为类似枚举的等价物,如下所示:
public class Constants {
private Constants() {
throw new AssertionError();
}
public interface ConstantType {}
public enum StringConstant implements ConstantType {
DB_HOST("localhost");
// other String constants come here
private String value;
private StringConstant(String value) {
this.value = value;
}
public String value() {
return value;
}
}
public enum IntConstant implements ConstantType {
DB_PORT(3128),
MAX_PAGE_SIZE(100);
// other int constants come here
private int value;
private IntConstant(int value) {
this.value = value;
}
public int value() {
return value;
}
}
public enum SimpleConstant implements ConstantType {
STATE_INIT,
STATE_START,
STATE_END;
}
}
这样我就可以把它们引用为:
Constants.StringConstant.DB_HOST
这是正确的做法。
通常,常量不会保存在单独的“常量”类中,因为它们是不可发现的。如果常量与当前类相关,那么保留它们有助于下一个开发人员。
我使用以下方法:
public final class Constants {
public final class File {
public static final int MIN_ROWS = 1;
public static final int MAX_ROWS = 1000;
private File() {}
}
public final class DB {
public static final String name = "oups";
public final class Connection {
public static final String URL = "jdbc:tra-ta-ta";
public static final String USER = "testUser";
public static final String PASSWORD = "testPassword";
private Connection() {}
}
private DB() {}
}
private Constants() {}
}
例如,我使用Constants.DB.Connection.URL来获取常量。 对我来说,它看起来更“面向对象”。