Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java switch using methods

I am wanting to call methods from an object from a switch statement.
Here, I am switching on a String:

switch (properties.getProperty("my.property")) { // getProperty() retuns a String
  case contains("something"):
    doSomething();
    break;
}

Can I execute methods of the switch'ed object like this? Basically I'm trying to avoid doing:

case properties.getProperty("my.property").contains("something"):

I'm pretty sure it's a lost cause, but perhaps I've missed something...

I've tried using contains() and .contains() to no avail. Should I just stop trying to be lazy? Or is there a way to do this?

like image 274
ddavison Avatar asked Feb 13 '23 14:02

ddavison


1 Answers

No, you can't. switch/case statements are for simple "this constant value maps to this set of actions; this constant value maps to this set of actions; ...".

If you need more complex processing, you should just use if statements.

like image 143
Jon Skeet Avatar answered Feb 15 '23 05:02

Jon Skeet