首页 > 解决方案 > 如何将方法签名从 void 更改为 CompletionStage?

问题描述

class AnotherClass {

    Option<Integer> validateAndGetInt(Xyz xyz, Mno mno, String strValue) {
        if (strValue != null) {
           int intValue = 1;
           
           try{
              intValue = Integer.parseInt(strValue);
           } catch (Exception e) {
              throw new Exception("err");
           }
       
           Printer.getInstance().validateInt(xyz, mno, intValue);

           return Optional.of(intValue);
        }
    }
} // class ends

class Printer {
   void validateInt(Xyz xyz, Mno mno, int x) {
      int m = xyz.getTeamVal(mno, x);
      if(m < 0) {
          throw new CustomException("invalid team value");
      }
   }
}

我计划从void搬到CompletionStage<Void>for validate(int x)

validate将更改如下,但我不确定如何在调用方使用。

  CompletionStage<Void> validateInt(Xyz xyz, Mno mno, int x) {
      CompletableFuture<Void> f = new CompletableFuture<Void>();
      int m = xyz.getTeamVal(mno, x);
      if(m < 0) {
          f.completeExceptionally(new CustomException("invalid team value"));
      } else {
          f.complete(null);
      }
      return f;
   }

有人可以帮助解释我如何使用它AnotherClass吗?

我不想尽可能多地使用它:

Printer.getInstance().validateInt(xyz, mno, intValue).toCompletableFuture().get()

标签: java-8futurecompletion-stage

解决方案


推荐阅读