0

让我给你一个具体的例子。

我有一个名为FutureConverter. 这个想法是能够转换CompletableFuture为另一种类型。如果您想在另一种 JVM 语言中使用我的库,这很有用。

我有一个返回的方法,CompletableFuture<MyClass>我想将返回类型转换为MyGenericFutureType<MyClass>. 但是,我不知道如何给出MyGenericFutureType参数。

我希望能够做这样的事情:

MyMainClass<FUTURE> {
    private final FutureConverter<FUTURE> converter;
    FUTURE<MyClass> myFunction() {
        //let's imagine soSomething is a method defined somewhere that returns CompletableFuture<MyClass>
        CompletableFuture<MyClass> myFuture = doSomething();
        return converter.convert(myFuture);
    }
}

现在类型参数FUTURE不知道他需要一个参数本身,所以它不会明显编译。

  1. 这甚至可能吗?
  2. 如果是,我该怎么做?

我知道 Java 类型系统可能会受到限制,但我希望这可以通过某种方式实现。

非常感谢您!

4

1 回答 1

0

定义你的FutureConverter接口如下:

public interface FutureConverter<S, T> {
    MyGenericFutureType<T> convert(CompletableFuture<S> source);
}

在您的具体转换器中(从CompletableFuture<Foo>MyGenericFutureType<Foo>只需实施FutureConverter<Foo>.

您可能还想看看 Spring 的转换器: https ://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#core-convert

https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/core/convert/converter/Converter.java

于 2017-03-12T10:40:31.327 回答