So can you do something like this in Java:
Can you get the value being switched on inside a switch expression
I have quite a few cases in my code which look like this (actual logic code removed for clarity reasons):
switch (weatherSystem.getRealClass().getSimpleName())
{
case "SyncWeatherSystem":
logger.info("initializing sync weather system");
…
break;
case "AsyncWeatherSystem":
logger.info("initializing async weather system");
…
break;
case "FixedWeatherSystem":
logger.info("initializing fixed weather system");
…
break;
case "NoWeatherSystem":
logger.info("initializing no weather system");
…
break;
}
And I really would love to do like:
switch (weatherSystem.getRealClass().getSimpleName())
{
case "SyncWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "AsyncWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "FixedWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "NoWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
}
Is this possible in Java?
No. It is not. But, weatherSystem.getRealClass().getSimpleName()
is. I suggest you save that value to a local variable. And all your case
(s) seem to do the same thing. So, as posted, you could simplify it. Like
String sName = weatherSystem.getRealClass().getSimpleName();
switch (sName)
{
case "SyncWeatherSystem":
case "AsyncWeatherSystem":
case "FixedWeatherSystem":
case "NoWeatherSystem":
logger.info("initializing {}", sName);
break;
}
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.