简体   繁体   English

在事实之后设置“恒定”

[英]set “constant” after the fact

I'm wanting to set a final variable after starting the constant. 我想在启动常量后设置最终变量。 This works if the variable is not final , but that kind of defeats the purpose. 如果变量不是final ,这将起作用,但是会破坏目的。

Can I do something similar to this? 我可以做类似的事情吗?

public static final String ASDF = null; 
{
    ASDF = "asdf";
}

My situation: 我的情况:

public static JSONArray CATEGORIES = null; 
{
    String str = "";
    str += "\"" + FIRST_CATEGORY + "\"";
    try {
        CATEGORIES = new JSONArray("[" + str + "]");
    } catch (JSONException e) {
        e.printStackTrace();
    }
};

You can use a static initialization block - at least, you can in regular Java SE (I'm assuing android can too): 您可以使用静态初始化块-至少可以在常规Java SE中使用(我也向android保证):

public static final JSONArray CATEGORIES;
static {
    String str = "\"" + FIRST_CATEGORY + "\"";
    try {
        CATEGORIES = new JSONArray("[" + str + "]");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Note that you are not first intializing CATEGORIES to null, it is left uninitialized until the static block happens. 请注意,您并不是首先将CATEGORIES初始化为null,直到静态块发生之前,它都未初始化。

Although, you're probably going to want to hard-fail if the intialization generates an exception, because otherwise you'll have an improperly initialized variable (serious problems possible). 虽然,如果初始化会产生异常,您可能会想要硬失败,因为否则您将拥有一个不正确的初始化变量(可能会出现严重的问题)。
And, unless the JSONArray class is immutable, declaring the instance final is ~sorta pointless. 并且,除非JSONArray类是不可变的,否则声明实例final是毫无意义的。

Figured it out. 弄清楚了。 I'm not exactly sure what's going on here, but it works. 我不确定这到底是怎么回事,但是可以。

public static final JSONArray CATEGORIES = new JSONArray() {
    {
        put(FIRST_CATEGORY);
        // etc eg. put(SECOND_CATEGORY);
    }
};

you can choose to not include "= null" on your variable declaration. 您可以选择在变量声明中不包含“ = null”。 just make sure that you assign a value to your variable once - be it inside an if-else, a loop, or whatever - the compiler will detect if you're breaking this rule, and won't let your program compile. 只需确保为变量分配一次值即可-可以在if-else,循环或其他内容中进行-编译器将检测您是否违反了该规则,并且不会让程序进行编译。

public static JSONArray CATEGORIES = null; 
{
    String str;
    str += "\"" + FIRST_CATEGORY + "\"";
    try {
        CATEGORIES = new JSONArray("[" + str + "]");
    } catch (JSONException e) {
        e.printStackTrace();
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM