English 中文(简体)
事实之后的“基本”
原标题:set "constant" after the fact
  • 时间:2011-11-01 16:38:08
  •  标签:
  • java
  • android

我不想在开始不变后确定最后变量。 如果变量不是final,而是这种变数打败了这个目的。

我能做些什么?

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();
    }
};
最佳回答

图2 我不确切地说,我会在这里看到什么,但会奏效。

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

您可以使用静态的初始化体,至少可以在 Java特区(I和roid):

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

请注意,在静态区块出现之前,你没有首先将<代码>CATEGORIES改为无效。

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.

你们可以选择不把“=无效”列入你可变的声明。 仅仅确保你一度给你的变数分配价值——无论是在哪里、在哪里,还是不管怎样——汇编者会发现,如果你重新打破这一规则,并赢得你的方案汇编。

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




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签