4 java methods switch-statement
这是我无法理解的东西,现在我有这样的东西:
boolean method1(int a){
//something
returns true;
}
boolean method2(int a){
//something
returns true;
}
for (int i; i<100; i++){
switch (someInt){
case 1: boolean x = method1(i);
case 2: boolean x = method2(i);
}
}
Run Code Online (Sandbox Code Playgroud)
我想要的是把开关带出循环,因为someInt将保持相同的每个i,因此需要只决定一次,但我需要x检查每一个,所以我需要像:
switch (someInt){
case 1: method1(); //will be used in loop below
case 2: method2(); //will be used in loop below
}
for (int i; i<100; i++){
boolean x = method the switch above picked
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Java 8方法引用.
这是一个例子:
public class WithMethodRefs {
interface MyReference {
boolean method(int a);
}
boolean method1(int a) {
return true;
}
boolean method2(int a) {
return false;
}
public void doIt(int someInt) {
MyReference p = null;
switch (someInt) {
case 1:
p = this::method1;
break;
case 2:
p = this::method2;
break;
}
for (int i = 0; i < 100; i++) {
p.method(i);
}
}
}
Run Code Online (Sandbox Code Playgroud)