使用通配符

时间:2018-02-23 12:02:09

标签: java generics casting unbounded-wildcard

我正在做静态的util方法,它使用空的optional:

返回已完成的future
public class CompletableFutureUtils {

    private static final CompletableFuture<Optional<?>> EMPTY_FUT = completedFuture(Optional.empty());

    private static final Optional<?> EMPTY_OPT = Optional.empty();

    @Nonnull
    @SuppressWarnings("unchecked")
    public static <T> CompletableFuture<Optional<T>> emptyOptionalCompletedFuture() {

        // COMPILE ERROR: incompatible types: CompletableFuture<Optional<?>> cannot be converted to CompletableFuture<Optional<T>>
        // return (CompletableFuture<Optional<T>>)EMPTY_FUT;

        return completedFuture((Optional<T>)EMPTY_OPT); // works, but creates new instance every time
    }
}

为了提高效率,我想返回已完成CompletableFuture - EMPTY_FUT 的相同常量实例,但由于无限制,无法将其转换为CompletableFuture<Optional<T>>通配符。

当然我想为任何类型调用这个完整的未来方法,与Optional.empty()CompletableFuture.completedFuture(U)几乎相同

如何使用无界通配符将泛型转换为特定类型?它有可能吗?

1 个答案:

答案 0 :(得分:5)

首先抛弃+-------------+------------+-------+--------+ | employee_id | date | hours | payment| +-------------+------------+-------+--------+ | 1 | 2018-01-01 | 8 | 40.0| | 1 | 2018-01-02 | 8 | 40.0| | 1 | 2018-01-03 | 8 | 40.0| | 1 | 2018-01-04 | 8 | 40.0| | 1 | 2018-01-05 | 8 | 40.0| | 1 | 2018-01-08 | 8 | 40.0| | 1 | 2018-01-09 | 8 | 40.0| | 1 | 2018-01-10 | 8 | 88.0| | 1 | 2018-01-11 | 8 | 88.0| | 1 | 2018-01-12 | 8 | 88.0| | 1 | 2018-01-15 | 8 | 96.0| | 1 | 2018-01-16 | 8 | 96.0| | 1 | 2018-01-17 | 8 | 96.0| | 1 | 2018-01-18 | 8 | 104.0| | 1 | 2018-01-19 | 8 | 104.0| +-------------+------------+-------+--------+ 的类型,然后再次投射到您想要的类型,如下所示:

CompleteableFuture