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"
l.setTime((String)v);
break;
(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 (§6.5.6.2) 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.
how to use a constant instead of a "xxxx"
You can't. JLS 14.11 :
Every case label has a case constant, which is either a constant expression or the name of an enum constant.
The name of a static final String
is not a constant expression.
You could use an enum
, as it says.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.