我的 generics-fu 很弱,但我认为应该是:
public static <T, R> Function<T, R> foo() {
// ...
}
但我认为你不能实例化R,你必须能够从T 获得它。您的代码不知道 R 的运行时类型,因此 new R() 超出范围。
但是例如,如果T 可以给你R,就像Map:
public static <K, R, T extends Map<K,R>> Function<T, R> makeGetter(K key) {
return a -> a.get(key);
}
这会返回一个 getter,当使用给定的 map 调用它时,将返回带有用于创建 getter 的键的条目:
import java.util.function.Function;
import java.util.*;
public class Example {
public static final void main(String[] args) {
Map<String,Character> mapLower = new HashMap<String,Character>();
mapLower.put("alpha", 'a');
mapLower.put("beta", 'b');
Map<String,Character> mapUpper = new HashMap<String,Character>();
mapUpper.put("alpha", 'A');
mapUpper.put("beta", 'B');
Function<Map<String, Character>, Character> getAlpha = makeGetter("alpha");
System.out.println("Lower: " + getAlpha.apply(mapLower));
System.out.println("Upper: " + getAlpha.apply(mapUpper));
}
public static <K, R, T extends Map<K,R>> Function<T, R> makeGetter(K key) {
return a -> a.get(key);
}
}
输出:
下:a
上:A
我认为类型擦除不能让你更接近,除非使用实例方法和参数化你的包含类。