我不知道这个标题是否可以理解,但是我有这个:
public class Product {
public Integer getId() {...}
public String getName() {...}
}
public <T,V> static void method(Function<T, V> f, V value) {...}
和I想成为编译错误时:
method(Product::getId, "some String"); // id is not String
method(Product::getName, 123); // name is not Integer
但是编译器将V解释为:
java Serializable & Comparable<? extends Serializable & Comparable<?>>
它可以编译,但取决于如何"method"你会在运行时得到一个异常,或者它只是错误地工作。
如何指示编译器匹配所需的数据类型?我不想写一个"方法">
谢谢!
您可以通过将泛型拆分为两个方法调用来执行泛型,为此您需要一个新类:
public class Value<T, V> {
private final Function<T, V> f;
public Value(Function<T, V> f) {
this.f= f;
}
public void with(V value) {
// move your code from method() into here
}
}
然后将method()
更改为如下内容:
public static <T, V> Value<T, V> method(Function<T, V> f) {
return new Value<>(f);
}
那么你可以这样使用:
method(Product::getId).with("123"); // compiler error
method(Product::getName).with(123); // compiler error
method(Product::getId).with(123); // no error
method(Product::getName).with("123"); // no error