soma soma - 3 years ago 107
Java Question

why public static final string can not used in java switch

java support switch a string, but in the case field, how to use a constant string?
Like this:

PhxLog l = new PhxLog();
for (String s : l.FIELDS) {
Object v = mapBaseData.getData().get(s);
switch (s) {
case l.LOG_FIELD_TIME: // this is wrong, but how to use a constant instead of a "xxxx"

Answer Source

(Credit goes to EJP's answer)

From JLS, it mentioned that expression you put in case needs to be a Constant Expression.

There are different form of Constant Expression, and String contants are in the list:

Qualified names (§ of the form TypeName . Identifier that refer to constant variables (§4.12.4).

From your code, it gives a hint that l.LOG_FIELD_TIME does not fulfill the requirement, because l is not a TypeName (hinted by for (String s : l) {). If LOG_FIELD_TIME is really a static final field, you should use ClassNameOfL.LOG_FIELD_TIME instead, and thing should work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download