Java 泛型,我如何定义一个需要是具有一个参数的泛型的类型?

Java generics, how can I define a type that needs to be a generics with one param?

举个具体的例子

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

我有一个 returns CompletableFuture<MyClass> 的方法,我想将 return 类型转换为 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 类型系统可能会受到限制,但我希望这是可能的。

非常感谢您!

按如下方式定义您的 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