[英]Can you refer to case values inside the code block of the switch statement?
So can you do something like this in Java:那么你能不能在 Java 中做这样的事情:
Can you get the value being switched on inside a switch expression 你能在 switch 表达式中获取被打开的值吗
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?这在 Java 中可能吗?
No. It is not.不它不是。 But,
weatherSystem.getRealClass().getSimpleName()
is.但是,
weatherSystem.getRealClass().getSimpleName()
是。 I suggest you save that value to a local variable.我建议您将该值保存到局部变量中。 And all your
case
(s) seem to do the same thing.你所有的
case
似乎都在做同样的事情。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.