我见过这样的例子:
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,我想知道这是否是创建常量的最佳方式。
当前回答
我这样做的方法之一是通过创建一个具有常量值的“全局”类,并在需要访问常量的类中进行静态导入。
其他回答
我同意大多数人所说的,在处理常量集合时最好使用枚举。然而,如果你在Android上编程,有一个更好的解决方案:IntDef Annotation。
@Retention(SOURCE)
@IntDef({NAVIGATION_MODE_STANDARD, NAVIGATION_MODE_LIST,NAVIGATION_MODE_TABS})
public @interface NavigationMode {}
public static final int NAVIGATION_MODE_STANDARD = 0;
public static final int NAVIGATION_MODE_LIST = 1;
public static final int NAVIGATION_MODE_TABS = 2;
...
public abstract void setNavigationMode(@NavigationMode int mode);
@NavigationMode
public abstract int getNavigationMode();
IntDef注释在一个简单的方面优于枚举,它占用的空间明显更少,因为它只是一个编译时标记。它不是一个类,也没有自动字符串转换属性。
这完全可以接受,甚至可能是标准。
(public/private) static final TYPE NAME = VALUE;
其中TYPE是类型,NAME是全大写的名称,空格用下划线表示,VALUE是常量值;
我强烈建议不要将常量放在它们自己的类或接口中。
附注:声明为final且为mutable的变量仍然可以更改;但是,变量永远不能指向不同的对象。
例如:
public static final Point ORIGIN = new Point(0,0);
public static void main(String[] args){
ORIGIN.x = 3;
}
这是合法的,ORIGIN将是(3,0)点。
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方法。
总之,以秒为单位的timeout值应该是一个配置设置(从属性文件中读取或像Spring中那样通过注入),而不是一个常量。
我不会称这个类与常量相同(除了大小写)…我将至少有一类“设置”,或“值”,或“常量”,所有的常量都将存在。如果我有很多,我会将它们分组在逻辑常量类中(UserSettings, AppSettings等)。