[英]Java constructor reference assignment Vs new created object assignment
I met in our project following code:我在我们的项目中遇到了以下代码:
MyInterface var = MyClass::new;
Is there difference with有区别吗
MyInterface var = new MyClass();
Lazy?懒惰的?
MyInterface var = new MyClass();
creates an instance of MyClass
and assigns it to a variable of type MyInterface
.创建
MyClass
的实例并将其分配给MyInterface
类型的变量。 This requires that MyClass implements MyInterface
and have a no-arg constructor.这要求
MyClass implements MyInterface
并具有无参数构造函数。 The result is an instance of MyClass
which implements MyInterface
however it likes to.结果是
MyClass
一个实例,它实现了MyInterface
但是它喜欢。
MyInterface var = MyClass::new;
attemps to implement MyInterface
ad-hoc.尝试实现
MyInterface
ad-hoc。 This requires that MyInterface
is a functional interface having a single abstract method.这要求
MyInterface
是一个具有单个抽象方法的功能接口。 That single abstract method must have a return type assignable from MyClass
and a parameter list matching one of MyClass
' constructors.该单个抽象方法必须具有可从
MyClass
分配的返回类型和与MyClass
的构造函数之一匹配的参数列表。
It is analog of:它是模拟的:
MyInterface var = new MyInterface() {
public MyClass anyMethodName() {
return new MyClass();
}
}
The result is an instance of MyInterface
which will on invocations of its single abstract method create a new instance of MyClass
passing all of its arguments to the constructor of MyClass
.结果是
MyInterface
一个实例,它将在调用其单个抽象方法时创建一个新的MyClass
实例,将其所有参数传递给MyClass
的构造函数。
In other words, these two constructs have nothing in common.换句话说,这两个结构没有任何共同点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.