1

Looking at a library called mongojack 3.0 - https://github.com/mongojack/mongojack. This library contains a file called JacksonMongoCollection.java It has a method...

  public JacksonCollectionKey<TResult> getCollectionKey() {
        return new JacksonCollectionKey<>(getMongoCollection().getNamespace().getDatabaseName(), getMongoCollection().getNamespace().getCollectionName(), getValueClass());
    }

This returns JacksonCollectionKey<>

This library compiles fine.

I have not seen an empty generic type definition before. How does this work?

4

2 回答 2

2

空的泛型类型括号用于编译器可以从上下文中推断出泛型类型。在您的情况下,编译器会将 TResult 插入空括号中。

于 2020-01-21T22:15:08.643 回答
2

这是 Java 中“类型推断”的一个示例。在某些情况下,可以省略显式类型信息,否则很明显缺少的类型是什么。

在您的示例中,该方法返回JacksonCollectionKey<TResult>,因此,没有必要指定类型参数,因为它是由返回类型给出的。

另一个常见的例子是:

List<String> list = new ArrayList<>();
于 2020-01-21T22:16:04.247 回答