您好,我现在的情况是需要使用多个 else if
并且我想使用 switch
语句,我已经尝试了很多,但我无法这样做。如何将以下 else if 转换为 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) {
}
}
最佳答案
使用 switch case 时,控制变量必须是基本类型、字符串或枚举。您不能在 switch-case 中使用对象。 来自 JLS:
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type
switch case 仅检查相等性(即类似于使用 == 运算符)。因此,您不能在 switch-case 中使用
instanceof
关于java - 如何用switch语句替换if else语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36426737/