2016-08-21 64 views
0

從它的父類方法退出子類方法執行給定下面的代碼片段:如何停止/ java中

超類的實現:

@Override 
    public void onDone(String taskName, JSONObject receivedData, @Nullable HashMap<String, String> sentData) { 
     //checks the status for all done process decides to call the presenter failed or success 
     try { 
      boolean success = receivedData.getString("status").equals("success"); 
      if(!success){ 
       this.presenter.error(receivedData.getString("reason")); 
      } 
     }catch (JSONException ex){ 
      ex.printStackTrace(); 
      this.presenter.error("An error occurred"); 
     } 
    } 

子類實現::

@Override 
    public void onDone(@NonNull String taskName, @NonNull JSONObject receivedData, 
         @Nullable HashMap<String, String> sentData) { 
     super.onDone(taskName, receivedData, sentData); 
     //the expected data has been received we should act upon it 
     //this DAO should know all the type of taskName it can handle and if it finds any that doesn't 
     //matches any of its command let it exit 
     Log.e(TAG, "Response : "+receivedData); 
     Toast.makeText(this.presenter.getContext(), "Done with task", Toast.LENGTH_LONG).show(); 
     if(sentData!=null){ 
      sentData.clear(); 
      sentData = null; 
     } 
    } 

我想要的是,只要super.onDone方法檢測到錯誤,該過程應該結束,不應該打擾運行子類方法,在JAVA中可能嗎?

+0

無關的評論:爲什麼即使抓住'JSONException',你可以在訪問它之前使用'receivedData.has(「status」)'' –

+0

這是因爲我的服務器將始終包含「狀態」鍵,狀態可以等於成功或失敗。所以,我需要知道是成功還是失敗。 –

+0

但是,只有在沒有「狀態」鍵的情況下才會觸發您正在捕捉的異常。 –

回答

3

你既可以

  • 有方法拋出一個異常(可能需要更大的重構來,然後用異常處理)

  • 有方法return false(改變返回類型從voidboolean )並在繼續之前檢查您的子類中的狀態。您也可以返回更詳細的狀態碼。

  • 讓超類將其處理狀態設置爲子類可以檢查的實例變量(this.wentWell = true)。這個缺點是它引入了可變狀態並且不是線程安全的。

  • (這是越來越糟糕的設計):讓超類更新HashMap它收到一些額外的信息爲子類拿起(sentData.put("wentWell", "true"))。這與servlet過濾器通過設置「請求屬性」來傳遞數據的方式類似。取決於可更新的地圖(情況並非如此),可能通過數據注入打開遠程攻擊(您正在將內部處理邏輯標誌放入可能直接來自誰知道位置的數據結構中)。

+0

嗯....好吧,需要確保...我希望那裏是除此之外的東西...但這很好......實際上也想到了最後一個選項,但是就像你說的那樣,它不是線程安全的......非常感謝..我想我會選擇第二個選項,這對我來說聽起來更合理。 –

+0

就此而言,第二個選項對我來說仍然是最好的選擇 –