Snorik
Snorik

Reputation: 211

Can you refer to case values inside the code block of the switch statement?

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?

Upvotes: 2

Views: 716

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201527

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;
}

Upvotes: 4

Related Questions