我今天遇到了一个好奇的语法。代码来自Gradle的源文件,您可以在src/core-impl/org/gradle/api/internal/artifacts/configurations/DefaultConfiguration.java
private class ConfigurationResolvableDependencies implements ResolvableDependencies {
public FileCollection getFiles() {
return DefaultConfiguration.this.fileCollection(Specs.<Dependency>satisfyAll());
}
}
是否有人能够解释这种奇怪的泛型语法的目的。如果这是重复,请原谅我,因为我不知道该怎么称呼它用于搜索目的。
答案 0 :(得分:1)
这里的语法是因为Specs
类的satisfyAll
方法是static
,所以Generics
语法指定了用于静态方法的类型。
请参阅此文档以获取API文档:http://www.gradle.org/docs/current/javadoc/org/gradle/api/specs/Specs.html#satisfyAll%28%29
答案 1 :(得分:0)
愚蠢的我,只需阅读documentation on the oracle website,这种类型的语法称为类型见证,当具有泛型类型的泛型方法定义如下时使用它:
public class BoxDemo {
public static <U> void addBox(U u, List<Box<U>> boxes) {
Box<U> box = new Box<>();
box.set(u);
boxes.add(box);
}
}
可以使用附加说明符调用该方法,告诉编译器推断第一个和第二个参数的参数类型:
List<Box<Integer>> listOfIntegerBoxes = new ArrayList<>();
BoxDemo.<Integer>addBox(Integer.valueOf(20), listOfIntegerBoxes);
也来自文档:
或者,如果省略类型见证,Java编译器会自动推断(来自方法的参数)类型参数为Integer:
BoxDemo.addBox(Integer.valueOf(20), listOfIntegerBoxes);