我希望能够在某个方法返回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[])这是因为我有很多检查案例,只是好奇,这样我就不必不必要地投掷
此类问题的解决方案通常是间接层。应该在Queue
和CompletableFuture
之间或CompletableFuture
和String[]
之间引入另一个对象。
Queue<Sometype> -> Sometype -> CompletableFuture<String[]> -> String[]
其中有针对不同CompletableFuture
类型的Sometype
实现
或
Queue<CompletableFuture<Sometype>> -> CompletableFuture<Sometype> -> Sometype -> String[]
其中有不同类型的Sometype
实现,例如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);
}