Java switch using methods

I want to call methods from an object from a switch statement.
Here I include String:

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

Can I execute object methods switch' ed like this? I mainly try to avoid:

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

I'm sure this is a lost cause, but maybe I missed something ...

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

+4
source share
3 answers

, . switch/case " , ...".

, if.

+6

, :

  switch("true") {
         case aFunctionThatReturnsTrueOrFalse():

 }

,

+1

@JonSkeet, switch , .

, , "" : , , switch . :

Pattern pattern = Pattern.compile("something|else");
Matcher matcher = pattern.matcher(properties.getProperty("my.property"));

switch(matcher.find() ? matcher.group() : "") {
case "something":
    doSomething();
    break;
case "else":
    doSomethingElse();
    break;
default:
    doDefault();
}

, if s:

if(prop.contains("something")) {
    doSomething();
} else if(prop.contains("else")) {
    doSomethingElse();
}

The second version is simpler and more understandable. Perhaps faster.

+1
source

Source: https://habr.com/ru/post/1546919/


All Articles