繁体   English   中英

Java 中 Kotlin 的“懒惰”相当于什么?

[英]What is the equivalent of Kotlin “by lazy” in Java?

我正在关注这篇文章https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c来实现 android 生命周期,但在 Java 上具有 Application 类的遗留应用程序上。

我如何在 Java 中实现这个 kotlin 代码?

private val lifecycleListener: SampleLifecycleListener by lazy {
    SampleLifecycleListener()
}

我觉得这是一个愚蠢的问题,但我不熟悉惰性初始化,我不知道如何搜索这个问题,任何“惰性理论链接”也将受到欢迎。

private SampleLifecycleListener sll;

public synchronized SampleLifecycleListener getSampleLifecycleListener() {
    if (sll == null) {
        sll = new SampleLifecycleListener();
    }
    return sll;
}

这样它在调用 getter 之前不会被初始化。

从 Java 8 开始,您可以使用ConcurrentHashMap#computeIfAbsent()来实现惰性。 ConcurrentHashMap是线程安全的。

class Lazy {
    private final ConcurrentHashMap<String, SampleLifecycleListener> instance = new ConcurrentHashMap<>(1);

    public SampleLifecycleListener getSampleLifecycleListener() {
        return instance.computeIfAbsent("KEY", k -> new SampleLifecycleListener()); // use whatever constant key
    }
}

你可以像这样使用

SampleLifecycleListener sll = lazy.getSampleLifecycleListener();

如果你想,你可以从 Java 调用 Kotlin lazy

import kotlin.Lazy;

Lazy<SampleLifecycleListener> lazyListener = kotlin.LazyKt.lazy(() -> new SampleLifecycleListener()));
SampleLifecycleListener realListener = lazyListener.getValue();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM