企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 2.3.2 构造函数引用 ```java static class Model { int height; Model() { } Model(int height) { this.height = height; } } ``` 对于没有参数的构造函数,可以使用: ```java Supplier<Model> m1 = Model::new; ``` 其等价于: ```java Supplier<Model> m1 = () -> new Model(); ``` ---- 对于签名是`Model(int height)`的构造函数,那么可以使用: ```java Function<Integer, Model> m2 = Model::new; ``` 其等价于: ```java Function<Integer, Model> m2 = i -> new Model(i); ``` ---- 为了避免Function对Model类中height属性造成的装箱拆箱操作,可以使用IntFunction: ```java IntFunction<Model> m3 = Model::new; ``` 其等价于: ```java IntFunction<Model> m3 = i -> new Model(i); ``` ---- 以下是本例的源码: ```java import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.Supplier; public class MethodReferenceTest { public static void main(String[] args) { Supplier<Model> m1 = Model::new; m1 = () -> new Model(); Function<Integer, Model> m2 = Model::new; m2 = i -> new Model(i); IntFunction<Model> m3 = Model::new; m3 = i -> new Model(i); } static class Model { int height; Model() { } Model(int height) { this.height = height; } } } ```