2

在这个例子中:

if (object instanceof SomeThing || object instanceof OtherThing) {
    System.out.println("this block was entered because of: " + **____** )
}

我可以检查真实情况是 SomeThing 还是 OtherThing?

编辑:我试图避免条件分离。

谢谢。

4

5 回答 5

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")
    );
}
于 2013-07-05T11:17:48.037 回答
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)
  }
于 2013-07-05T11:17:22.237 回答
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: " + **____** )
}
于 2013-07-05T11:17:29.973 回答
0

尝试使用三元运算符:

 if (object instanceof SomeThing || object instanceof OtherThing) {
        System.out.println("this block was entered because of: " 
           + (object instanceof SomeThing? "SomeThing" : "OtherThing") );
    }
于 2013-07-05T11:20:08.713 回答
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")
}
于 2013-07-05T11:30:58.667 回答