在这个例子中:
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println("this block was entered because of: " + **____** )
}
我可以检查真实情况是 SomeThing 还是 OtherThing?
编辑:我试图避免条件分离。
谢谢。
在这个例子中:
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println("this block was entered because of: " + **____** )
}
我可以检查真实情况是 SomeThing 还是 OtherThing?
编辑:我试图避免条件分离。
谢谢。
将这两种情况下的任何常见步骤重构为一个函数,然后:
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")
);
}
尝试
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)
}
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: " + **____** )
}
尝试使用三元运算符:
if (object instanceof SomeThing || object instanceof OtherThing) {
System.out.println("this block was entered because of: "
+ (object instanceof SomeThing? "SomeThing" : "OtherThing") );
}
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")
}