简体   繁体   中英

Cast constant generic with wildcard

I'm doing static util method which returns completed future with empty optional:

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

For the sake of efficiency i want to return the same constant instance of completed CompletableFuture - EMPTY_FUT , but can't cast it to CompletableFuture<Optional<T>> because of unbounded wildcard.

Of course i want to call this completed future method for any type, pretty much the same as Optional.empty() and CompletableFuture.completedFuture(U)

How to cast generic with unbounded wildcard to specific type? Is it possible at all?

首先丢弃CompleteableFuture的类型,然后再次转换为您想要的类型,如下所示:

return (CompletableFuture<Optional<T>>) (CompletableFuture<?>) EMPTY_FUT;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM