方法引用不能直接实现属性拷贝,仅能通过Function接口简化属性读取,需配合BiConsumer等完成“读-写”逻辑,适用于类型安全、无反射的轻量级字段映射。
Java 中方法引用本身不能直接实现属性拷贝,但它可以配合 java.util.function 中的函数式接口(如 Function)简化属性提取逻辑,在手动或自定义拷贝场景中提升可读性和复用性。
属性拷贝本质是「读取源对象字段 → 写入目标对象字段」的过程。方法引用(如 Person::getName)只能表示一个无参、返回值为属性的函数(即 Function<person string></person>),它只解决「怎么读」,不涉及「怎么写」或「如何映射」。
Function<S, T> 表示从源类型 S 到目标类型 T 的属性访问路径target.setName(source.getName()) 就能靠方法引用自动完成——这仍需显式调用 setterFunction<User, String> nameGetter = User::getUsername;,后续可用于统一提取字段你可以用方法引用 + Lambda 封装「读-写」逻辑,避免重复手写 getter/setter 调用:
(source, target) -> target.setName(source.getName())
Function<User, String> getName = User::getUsername;,再配合 setter 的 Lambda 使用Function<User, String> getName = User::getUsername;<br>BiConsumer<Admin, String> setName = Admin::setUsername;<br>setName.accept(target, getName.apply(source));
若不想依赖第三方库(如 BeanUtils、MapStruct),可设计轻量级拷贝工具,将方法引用作为配置传入:
立即学习“Java免费学习笔记(深入)”;
new FieldMapping<>(User::getAge, Admin::setAge)
FieldMapping,遍历执行 setter.accept(target, getter.apply(source))
user::getProfile::getPhone 需封装为 Lambda,因方法引用不支持链式调用)方法引用虽简洁,但有明确适用边界:
LocalDateTime → String),需额外包装或使用更通用的 converter