您好我处于需要使用多个else if's
并且我想使用switch
语句的情况,我已经尝试了很多,但我无法这样做。如果要切换,我该如何转换以下其他内容?
public ApiObservables(Object o) {
if (o instanceof SitesController) {
mSitesApi = getSitesApi();
} else if (o instanceof QuestionController) {
mQuestionApi = getQuestionApi();
} //more else if's
}
我想做这样的事情:
public ApiObservables(Object o) {
switch (o) {
}
}
答案 0 :(得分:2)
使用switch case时,控制变量必须是基本类型,或String或枚举。您不能在switch-case中使用对象。 来自JLS:
Expression的类型必须是char,byte,short,int,Character,Byte,Short,Integer,String或enum类型
switch case仅检查相等性(即类似于使用==运算符)。因此,您无法在switch-case
instanceof
答案 1 :(得分:1)
在你的情况下,我会使用方法重载:
public ApiObservables foo(Object o) {
//throw new IllegalArgumentException?
}
public ApiObservables foo(SitesController o) {
return getSitesApi();
}
public ApiObservables foo(QuestionController o) {
return getQuestionApi();
}
答案 2 :(得分:1)
我不知道你是否可以重构你的代码但是使用接口的不同方法呢?像这样:
interface API {
//method signatures here
}
class SitesApi implements API {
//implementation here
}
class QuestionApi implements API {
//implementation here
}
interface Controller {
API getAPI();
}
class QuestionController implements Controller {
@Override
public API getAPI() {
return new QuestionAPI();
}
}
class SitesController implements Controller {
@Override
public API getAPI() {
return new SitesAPI();
}
}
然后:
public ApiObservables(Controller controller) {
someApi = controller.getAPI();
}
答案 3 :(得分:0)
I don't know about your remaining code try this by passing in this function repective controller string as per your object
and if you use object in switch case then i think it will not support
try this one
public ApiObservables(String o) {
switch(o) {
case "SitesController":
mSitesApi = getSitesApi();
break;
case "QuestionController":
mQuestionApi = getQuestionApi();
default:
System.out.println("place any thing that you want to show any message");
break;
}
}