2013-07-05 31 views
2

在這個例子中:有沒有辦法找出哪個IF條件'觸發'入口if(){} block?

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

我可以檢查是否真正的條件是什麼或OtherThing?

編輯:我試圖避免條件分離。

謝謝。

+4

創建第二個'if'。 –

+0

分開你的'if'條件。 – eternay

+0

或者可能在System.out.println中使用三元操作符 – MohamedSanaulla

回答

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") 
    ); 
} 
+0

謝謝,第二個選項對我來說最好,我忘了提及兩個條件都有常見的第二個條件,_object_的屬性,以便現在會進入頂層IF。例如:if(object.property == 1){*檢查對象instanceof *} –

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) 
    } 
+0

@TJCrowder編輯時我收到你的評論:) –

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: " + **____**) 
} 
0

嘗試使用三元運算符:

if (object instanceof SomeThing || object instanceof OtherThing) { 
     System.out.println("this block was entered because of: " 
      + (object instanceof SomeThing? "SomeThing" : "OtherThing")); 
    } 
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") 
} 
相關問題