在这个例子中:
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println("this block was entered because of: " + **____** )
}
我可以检查真实情况是SomeThing还是OtherThing?
编辑:我正试图避免条件分离。
感谢。
答案 0 :(得分:3)
将两种情况下的任何常见步骤重构为函数,然后:
if (object instanceof SomeThing) {
// It's SomeThing
System.out.println("Got here because it's SomeThing");
commonStuff();
}
else if (object instanceof OtherThing) {
// It's OtherThing
System.out.println("Got here because it's OtherThing");
commonStuff();
}
重新编辑:
编辑:我正试图避免条件分离。
然后你有这些选择:
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println("Got here because it's " +
(object instanceof SomeThing) ? "SomeThing" : "OtherThing")
);
}
或者
boolean isSomeThing:
if ((isSomeThing = object instanceof SomeThing) || object instanceof OtherThing) {
System.out.println("Got here because it's " +
isSomeThing ? "SomeThing" : "OtherThing")
);
}
答案 1 :(得分:1)
尝试
if (object instanceof SomeThing ) {
System.out.println("this block was entered because of: " + **SomeThing ____** )
}
else if(object instanceof OtherThing){
System.out.println("this block was entered because of: " + **OtherThing____** )
}
else{
System.out.println("********nothing satisfied)
}
答案 2 :(得分:0)
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println(object instanceof SomeThing );// if this print false then object is type of OtherThing
System.out.println("this block was entered because of: " + **____** )
}
答案 3 :(得分:0)
尝试使用三元运算符:
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println("this block was entered because of: "
+ (object instanceof SomeThing? "SomeThing" : "OtherThing") );
}
答案 4 :(得分:0)
System.out.println("This block was entered because object is instance of SomeThing or OtherThing.");
作为替代方案:
System.out.println("This block was entered because object is " + object.getClass().getName());
或者,非常不可读:
boolean other = false;
if (object instanceof SomeThing || (other = true) || ....) {
System.out.println("because of " + other?"OtherThing":"SomeThing")
}