在Java中发布全局常量的更好的方法是什么? [英] What is the better way of publishing global constants in Java?

查看:172
本文介绍了在Java中发布全局常量的更好的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发布全局常量的哪种方式之一更好?谢谢!!!

Which one of these ways of publishing global constants is better? THANKS!!!

方法1:具有公共静态终场的最终课

public final class CNST{
    private CNST(){}
    public static final String C1;
    public static final String C2;
    static{
       C1="STRING1";
       C2="STRING2";
    }
}
//so I could call C1, C2 like:
//...some code...
//System.out.println(CNST.C1);
//System.out.println(CNST.C2);

方法2:带枚举的单例 p>

Method 2: singleton with enum

public enum CNST{
    INST;
    public final String C1;
    public final String C2;
    CNST{
       C1="STRING1";
       C2="STRING2";
    }
}
//so I could call C1, C2 like:
//...some code...
//System.out.println(CNST.INST.C1);
//System.out.println(CNST.INST.C2);


推荐答案

遵循更常规惯例的东西就是这样:

Something that follows more usual conventions would be like this:

public class MyAppConstants {
    public static final String C1 = "STRING1";
    public static final String C2 = "STRING2";
}

然后你可以这样引用它:

Then you can refer to it later like this:

System.out.println(MyAppConstants.C1);

但是如果我不得不选择两者之间给我,我想我会选择第一个,因为枚举是有误导性的,并不能在功能上有所帮助,也不会使代码更清晰。

But if I had to pick between the two you give I guess I would choose the first, because the enum is misleading and doesn't help functionally and doesn't make the code clearer.

这篇关于在Java中发布全局常量的更好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆