静态函数调用前的泛型尖括号
Generics angle brackets before static function call
我一直使用泛型并且总是看到像这样使用尖括号:Class<Type>
(例如List<String>
)。
今天我在调用静态方法之前遇到了泛型规范,例如:Class.<TypeA, TypeB>staticCall()
。真实的例子是:ImmutableMap.<String, String>builder()
.
我没见过这种用法,在documentation中也找不到这种具体用法。有人可以解释一下这是怎么回事吗?
表示多种类型。 List 只采用一种通用类型,这就是为什么您会看到
List<String>
来自 Map
的 java 文档
在顶部您会看到:
界面图
所以需要两个 generic types。在不可变映射的示例中,它表示 K(ey) 是一个字符串,而 V(alue) 也是一个字符串。
在您提供的 link 中,它提到在
部分下这是可能的
A Generic Version of the Box Class
这些被称为Generic Methods。
在 Java 7 之前,您必须指定通用引用的类型:
Util.<Integer, String>compare(p1, p2);
现在编译器从上下文推断类型。
我们也可以在 class 级别定义泛型。
ImmutableMap.Builder 表示 Builder 是 inner static class 这里 .
并且 Builder 方法将以 K 和 V 作为参数意味着
意味着代替提供 put(String , String) 它提供像 put(K,V) 这样的方法,这样任何类型都可以使用 put 添加,如果你得到你需要使用相同的类型。
例如,如果您通过传递 string 和 String 来调用 Builder.Put,那么在 get 中我们可以直接分配给 String
字符串值 = Bullder.get(K);
这意味着 ImmutableMap.Builder 的所有方法都适用于任何 class 类型。
这就是泛型的强大之处,意味着无需为不同的类型覆盖方法。
只需像下面这样定义:
public Builder<K, V> put(K key, V value) {
ensureCapacity(size + 1);
ImmutableMapEntry<K, V> entry = entryOf(key, value);
// don't inline this: we want to fail atomically if key or value is null
entries[size++] = entry;
return this;
}
我一直使用泛型并且总是看到像这样使用尖括号:Class<Type>
(例如List<String>
)。
今天我在调用静态方法之前遇到了泛型规范,例如:Class.<TypeA, TypeB>staticCall()
。真实的例子是:ImmutableMap.<String, String>builder()
.
我没见过这种用法,在documentation中也找不到这种具体用法。有人可以解释一下这是怎么回事吗?
表示多种类型。 List 只采用一种通用类型,这就是为什么您会看到
List<String>
来自 Map
的 java 文档在顶部您会看到: 界面图
所以需要两个 generic types。在不可变映射的示例中,它表示 K(ey) 是一个字符串,而 V(alue) 也是一个字符串。
在您提供的 link 中,它提到在
部分下这是可能的A Generic Version of the Box Class
这些被称为Generic Methods。
在 Java 7 之前,您必须指定通用引用的类型:
Util.<Integer, String>compare(p1, p2);
现在编译器从上下文推断类型。
我们也可以在 class 级别定义泛型。
ImmutableMap.Builder 表示 Builder 是 inner static class 这里 .
并且 Builder 方法将以 K 和 V 作为参数意味着
意味着代替提供 put(String , String) 它提供像 put(K,V) 这样的方法,这样任何类型都可以使用 put 添加,如果你得到你需要使用相同的类型。
例如,如果您通过传递 string 和 String 来调用 Builder.Put,那么在 get 中我们可以直接分配给 String
字符串值 = Bullder.get(K);
这意味着 ImmutableMap.Builder 的所有方法都适用于任何 class 类型。
这就是泛型的强大之处,意味着无需为不同的类型覆盖方法。 只需像下面这样定义:
public Builder<K, V> put(K key, V value) {
ensureCapacity(size + 1);
ImmutableMapEntry<K, V> entry = entryOf(key, value);
// don't inline this: we want to fail atomically if key or value is null
entries[size++] = entry;
return this;
}