相关疑难解决方法(0)

在Java中实现常量的最佳方法是什么?

我见过这样的例子:

public class MaxSeconds {
   public static final int MAX_SECONDS = 25;
}
Run Code Online (Sandbox Code Playgroud)

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

java constants

373
推荐指数
12
解决办法
67万
查看次数

是否所有编译时常量都内联?

假设我有这样一个类:

class ApplicationDefs{
public static final String configOption1 = "some option";
public static final String configOption2 = "some other option";
public static final String configOption3 = "yet another option";
}
Run Code Online (Sandbox Code Playgroud)

我的应用程序中的许多其他类都使用这些选项.现在,我想单独更改其中一个选项并仅部署已编译的类.但是,如果这些领域在消费者类中被列入,这就变得不可能了吗?

是否有任何选项可以禁用编译时常量的内嵌?

java inlining compile-time-constant

22
推荐指数
5
解决办法
6607
查看次数

在构造函数中初始化public static final变量

我正在尝试Version为我的应用程序创建一个类,它将在加载时从清单中读取版本号,然后仅参考例如Version.MAJOR我在其他地方需要它的地方.但是,我遇到了这样的问题.这是我目前的代码:

 public class Version {

    public static final int APPCODE;
    public static final int MAJOR;
    public static final int MINOR;
    public static final char RELEASE;
    public static final int BUILD;

    static {

        try {
            Class clazz = Version.class;
            String className = clazz.getSimpleName() + ".class";
            String classPath = clazz.getResource(className).toString();
            if (classPath.startsWith("jar")) {
                String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
                Manifest manifest = new Manifest(new URL(manifestPath).openStream());
                Attributes attr = manifest.getMainAttributes();
                APPCODE = Integer.parseInt(attr.getValue("APPCODE"));
                MAJOR = Integer.parseInt(attr.getValue("MAJOR")); …
Run Code Online (Sandbox Code Playgroud)

java initialization constants manifest static-classes

3
推荐指数
1
解决办法
3787
查看次数