
在Java 8 引入了函数式接口后,Supplier 接口变得非常常用,它代表一个无参数的函数,返回一个结果。在某些场景下,我们可能需要将当前对象 this 传递给一个 Supplier。本文将探讨几种实现方式,并分析它们的优劣。
问题背景与需求
假设我们有一个类 Thing<T>,它包含一个值和一个 CompletableFuture<T>。CompletableFuture 的完成依赖于其他组件的状态。我们希望使用 completeAsync() 方法来异步地完成 CompletableFuture,并将 this 对象传递给 Supplier。
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
class Thing<T> {
final T value;
final CompletableFuture<T> future;
Thing(T value) {
this.value = value;
this.future = new CompletableFuture<>();
}
Thing<T> self() {
return this;
}
void reject() {
future.cancel(false);
}
void complete() {
// 方式一:使用 Lambda 表达式
future.completeAsync(() -> this);
// 方式二:使用方法引用
future.completeAsync(this::self);
}
}在上述代码中,我们使用了两种方式将 this 传递给 Supplier:
立即学习“Java免费学习笔记(深入)”;
Lambda 表达式 vs. 方法引用
这两种方式都能达到将 this 传递给 Supplier 的目的,但它们之间存在细微的差异。
最佳实践与注意事项
虽然上述两种方式都能实现将 this 传递给 Supplier 的目的,但在大多数情况下,直接在需要 this 的地方使用 this 即可。
例如,如果 CompletableFuture 完成后需要访问 Thing 对象的其他字段,可以直接在 Lambda 表达式或 self() 方法中访问 this.value 或调用 this.otherMethod()。
class Thing<T> {
final T value;
final CompletableFuture<T> future;
Thing(T value) {
this.value = value;
this.future = new CompletableFuture<>();
}
void complete() {
future.completeAsync(() -> {
// 直接访问 this.value
System.out.println("Value: " + this.value);
return this;
});
}
}总结
将 this 传递给 Supplier 可以通过 Lambda 表达式或方法引用实现。方法引用通常更简洁、可读性更强,并且可能略微高效。然而,在大多数情况下,直接在需要 this 的地方使用 this 即可,避免不必要的复杂性。选择哪种方式取决于具体的场景和个人偏好。 关键在于保持代码的清晰性和可维护性。
以上就是如何在Java中将 this 传递给 Supplier的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号