Jacksonkr
Jacksonkr

Reputation: 32247

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.

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();
    }
};

Upvotes: 2

Views: 98

Answers (3)

Jacksonkr
Jacksonkr

Reputation: 32247

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);
    }
};

Upvotes: 1

josephus
josephus

Reputation: 8304

you can choose to not include "= null" on your variable declaration. 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.

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

Upvotes: 0

Clockwork-Muse
Clockwork-Muse

Reputation: 13086

You can use a static initialization block - at least, you can in regular Java SE (I'm assuing android can too):

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.

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.

Upvotes: 3

Related Questions