在查看一些 Java 8 代码时,我看到了一些我不太理解的泛型的使用,因此我编写了自己的代码来模拟正在发生的事情:
public class GenericsTest {
public static void main(String[] args) {
TestBuilder tb = TestBuilder.create(Test_Child::new);
Product<Test_Child> p = tb.build();
Test tc = p.Construct("Test");
}
static class TestBuilder<T extends Test> {
private final Factory<T> f;
public TestBuilder(Factory<T> f) {
this.f = f;
}
public static <T extends Test> TestBuilder<T> create(Factory<T> f){
return new TestBuilder<>(f);
}
public Product<T> build(){
return new Product<>(f);
}
}
static class Test {
public Test(){
}
}
static class Test_Child extends Test{
public Test_Child(String s){
System.out.println("Test_Child constructed with string '"+s+"'");
}
}
interface Factory<T extends Test> {
T create(String s);
}
static class Product<T extends Test>{
private Factory<T> f;
public Product(Factory<T> f) {
this.f = f;
}
public T Construct(String s){
return f.create(s);
}
}
}
运行此打印:
Test_Child constructed with string 'Test'
我不明白的是:
Test_Child::new
提供参数f.create()
在 Product
实例指的是Test_Child
的构造函数类(class)。 最佳答案
How you don't have to provide arguments to Test_Child::new
因为它是 lamda 表示的方法引用
s -> new Test_Child(s)
可以创建为 Factory
界面最终变成了 FunctionalInterface
根据其定义。How calling f.create() in the Product instance refers to the constructor of the Test_Child class.
因为那是通过
TestBuilder
传递的实例类型, 至 Product
两者都有一个属性 Factory<Test_Child>
.当您将作业重写为TestBuilder<Test_Child> tb = TestBuilder.create(Test_Child::new)
进一步解释为代码内嵌的注释
TestBuilder tb = TestBuilder.create(Test_Child::new); TestBuilder
// TestBuilder<Test_Child> is build with a Factory<Test_Child> attribute
Product<Test_Child> p = tb.build();
// We have build a Product<Test_Child> which has a Factory<Test_Child> attribute from above
Test tc = p.Construct("Test");
// invokes the 'create' method of the Factory which calls 'new Test_Child(s)' to print the output
关于java - 使用泛型构造子类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60896483/