【问题标题】:How do I create a casted type of an object from the returned result of a different object如何从不同对象的返回结果创建对象的强制类型
【发布时间】:2018-12-22 11:23:09
【问题描述】:

如果某个方法返回String[],我希望能够将CompletableFuture<?> 转换为CompletableFuture<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[]) 这是因为我有很多检查用例,只是很好奇,所以我不必进行不必要的投射

【问题讨论】:

    标签: java generics casting wildcard


    【解决方案1】:

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

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

    对于不同的CompletableFuture 类型有Sometype 实现

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

    哪里有针对不同类型的Sometype 实现,例如String[]

    【讨论】:

    • 好的,但是如果他想把它转换成 String[] 以外的东西怎么办?然后呢?
    • @MS90 你有多个Sometype 实现。其中一些可能使用String[]其中一些其他类型。
    【解决方案2】:

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

      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);
      }
    

    【讨论】:

    • 这是一个很好的解决方案,但遗憾的是不安全!
    • 不安全我很好,我会完成异常,为此欢呼,如此简单,我肯定过度复杂了哈哈
    猜你喜欢
    • 2016-02-16
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多