2016-08-21 66 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

就此而言,第二个选项对我来说仍然是最好的选择 –