在Java 8+ 中,Function.identity() 可以方便地返回输入对象本身,相当于 t -> t。 然而,对于 Supplier 接口,我们可能需要一个返回 this 的函数,即 () -> this。 虽然Java标准库没有提供直接的预定义函数来实现这个目的,但我们可以使用Lambda表达式或方法引用来达到同样的效果。
最直接的方式是使用Lambda表达式:
Supplier<MyClass> supplier = () -> this;
这种方式简单明了,能够清晰地表达意图。但是,在某些性能敏感的场景下,每次调用都可能导致Lambda表达式的实例化,产生一定的开销。
另一种方式是使用方法引用。 首先,在类中定义一个返回 this 的方法:
立即学习“Java免费学习笔记(深入)”;
class MyClass { MyClass self() { return this; } void doSomething(Supplier<MyClass> supplier) { // ... } }
然后,可以使用方法引用将 this::self 传递给 Supplier:
MyClass instance = new MyClass(); instance.doSomething(instance::self);
方法引用 instance::self 本质上也是一个 Supplier
考虑一个 CompletableFuture 的使用场景:
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.complete(() -> this); // 使用方法引用 future.complete(this::self); } }
在这个例子中,complete() 方法使用 CompletableFuture.completeAsync(Supplier extends T>) 来异步完成 future。 两种方式都可以将 this 传递给 Supplier,但使用方法引用 this::self 可能会稍微减少对象分配的开销。
总而言之,虽然Java没有提供像 Function.identity() 这样的预定义函数来返回 this,但我们可以通过Lambda表达式或方法引用来实现相同的功能。 在选择具体实现方式时,应综合考虑可读性和性能因素,并根据实际情况进行选择。
以上就是如何在Java中将this传递给Supplier的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号