java - 使用泛型构造子类的实例

标签 java generics java-8

在查看一些 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/

    相关文章:

    java - Java 中的通用数组的正确方法

    Java 泛型 : actual class as a generic parameter

    java - Java 中的动态泛型类型

    用于计算唯一对象的 Java lambda 表达式

    Java 8 流 - 将方法传递给过滤器

    java - 如何应用、删除和重新应用 bytebuddy 转换?

    java - 尝试更改字体时出现 Digitalclock 运行时错误

    java - 获取特定时区中的当前 Instant

    java - 在异步任务前/后执行方法中使用 ProgressDialog

    Linux 服务器上的 Java jdbc 类路径