【发布时间】:2019-09-19 01:59:30
【问题描述】:
package com.test.lambda;
import java.util.function.Supplier;
class Document {
void printAuthor() {
System.out.println("Document-Author");
}
}
class RFP extends Document {
@Override
void printAuthor() {
System.out.println("RFP-Author");
}
}
public class TestLambda1 {
public static void function21() {
Supplier<Document> s1 = Document::new; // working
Supplier<Document> s2 = RFP::new; // (1)
Supplier<? extends Document> s3 = Document::new; // working
Supplier<? extends Document> s4 = RFP::new; // working
Supplier<? super Document> s5 = Document::new; // working
Supplier<? super Document> s6 = RFP::new; // (2)
Supplier<? super RFP> s7 = Document::new; // (3)
Supplier<? super RFP> s8 = RFP::new; // working
}
public static void main(String[] args) throws Exception {
function21();
}
}
(1) (2) & (3) 中的问题是,它应该像 java 1.7 一样工作 (1) :它应该给出错误,因为应该只接受文档类型。 (2) :它应该给出错误,因为应该只接受超类型的 Document。 (3) : 它应该作为 RFP 的 super 可以保存 Document 对象。 Difference between <? super T> and <? extends T> in Java
【问题讨论】:
-
链接答案的哪一部分不能关联?因为这些答案已经很详细了。
-
显然,类型推断非常复杂,但我希望 (1) 和 (2) 能够工作。毕竟,
RFP::new确实会产生一个 Document 对象。我同意(3)应该有效。您实际上可以转换它,(Supplier<Document>) Document::new,它会编译而不会出现任何错误或警告。 -
@VGR 在这种情况下,它并不复杂。这是由于语言设计者为了避免(甚至更高的)复杂性而故意削减的。
标签: java generics lambda java-8 method-reference