Java 方法签名中未使用的泛型类型

Java Generic Types in Method signature which are not used

当在方法中未使用泛型类型时,在方法签名中指定泛型类型有什么用,例如考虑以下来自 Kafka Materialized 的方法:

public static <K, V, S extends StateStore> Materialized<K, V, S> as(String storeName) {
    Named.validate(storeName);
    return new Materialized(storeName);
}

private Materialized(String storeName) {
    this.storeName = storeName;
}

此处方法中未使用类型 K、V、S。

Github link for materialized class

What is the use of specifying Generic types in the method signature when they are not getting used in the method

您实际上(或应该)在方法中使用它们:

return new Materialized(storeName);

这是原始类型。这是 the source code you linked:

的转录错误
return new Materialized<>(storeName);

是 shorthand 用于:

return new Materialized<K, V, S>(storeName);

但是无论如何,仅在 return 类型中使用的方法类型变量会在您调用该方法后使用。

例如,在方法中创建 ArrayList<T> 允许您将 T 的实例添加到结果中。

<T> List<T> myMethod() {
  return new ArrayList<>();
} 

// At the call site:
List<String> list = myMethod();
list.add("Hello");

Materialized 的情况下,这给出了关于根据这些类型变量声明的字段的类型信息:Serde<K> keySerdeSerde<V> valueSerdeStoreSupplier<S> storeSupplier;然后 Kafka 可以访问 fields/methods 这些字段,这些字段使用特定类型进行操作。