如何根据不同对象的返回结果创建对象的强制转换类型

How do I create a casted type of an object from the returned result of a different object

我希望能够施放一个CompletableFuture<?> 说一个CompletableFuture<String[]> if 某个方法returns一个String[]

所以我有一个来自队列的 CompletableFuture<?>,我想知道如何正确地转换它而不必总是检查我的具体情况

这是我目前拥有的...

    CompletableFuture<?> cb = cbQueue.poll();

    switch(subChannel) {
        case "GetServers":
            ((CompletableFuture<String[]>) cb).complete(in.readUTF().split(", "));
            break;
    }

但是我只想写...

    CompletableFuture<?> cb = cbQueue.poll();

    switch(subChannel) {
        case "GetServers":
            complete(cb, in.readUTF().split(", "));
            break;
    }

并且它会根据传递的类型进行适当的转换(在本例中为 String[]) 这是因为我有很多检查用例,只是好奇所以我不必不必要地投射

您可以添加一个辅助方法...由于未经检查的转换,这仍然有可能在运行时出错

  public void stuff() {

    CompletableFuture<?> c = new CompletableFuture<String>();

    complete(c,"bla");

  }

  private static <T> void complete(CompletableFuture<?> c, T value) {
    ((CompletableFuture<T>) c).complete(value);
  }

像这样的问题的解决方案通常是一个间接层。应在 QueueCompletableFuture 之间或 CompletableFutureString[] 之间引入另一个对象。

Queue<Sometype> -> Sometype -> CompletableFuture<String[]> -> String[]

其中有 Sometype 不同 CompletableFuture 类型的实现

Queue<CompletableFuture<Sometype>> -> CompletableFuture<Sometype> -> Sometype -> String[]

其中有 Sometype 不同类型的实现,例如 String[]