Java 8 构造函数引用的类型是什么



使用以下模型:

package supplier;
public interface Shape {
    void draw();
    public static class Rectangle implements Shape {
        @Override
        public void draw() {
            System.out.println("Inside Rectangle::draw() method.");
        }
    }
    public static class Circle implements Shape {
        @Override
        public void draw() {
            System.out.println("Inside Circle::draw() method.");
        }
    }
    public static class Square implements Shape {
        @Override
        public void draw() {
            System.out.println("Inside Square::draw() method.");
        }
    }
}

我试图了解 Java 如何确定构造函数引用返回的 lambda 表达式的类型:

    Shape square = Square::new;
    System.out.println("square: "+square);
    Supplier<Shape> suppSquare = Square::new;
    System.out.println("suppSquare: "+suppSquare);

square: supplier.ShapeFactoryTest$$Lambda$11/183264084@1c655221
suppSquare: supplier.ShapeFactoryTest$$Lambda$12/1490180672@1b701da1

这两种情况似乎都返回 lambda,但以下内容无法编译:

square = suppSquare;

那么在第一种情况下,如何将 lambda 解析为底层类型?

您的 Shape 接口是一个函数接口,因为它有一个抽象方法draw() 。此方法不接受任何参数,并且不返回任何内容。因此,它类似于可运行。

Square 的构造函数不接受任何参数,它"返回"(或者更确切地说,创建(的内容可以忽略。因此,它可以用作Shape功能接口的实现:它的签名是兼容的。这就是为什么您可以使用

Shape square = Square::new;

它定义了类型 Shape 的变量square

不过这没有多大意义,因为当在变量square上调用 draw(( 时,您可能会期望发生一些绘制。但这不会发生。Square的构造函数将被调用,仅此而已。

和做

square = suppSquare;

不可能工作,因为 square 是 Shape 类型的变量,而 Shape 不是 Supplier<Shape> 的超类型。

最新更新