简体   繁体   English

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

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

I'm following this article https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c to implement android lifecycle but on a legacy app that has the Application class on java.我正在关注这篇文章https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c来实现 android 生命周期,但在 Java 上具有 Application 类的遗留应用程序上。

How can I implement this kotlin code in java?我如何在 Java 中实现这个 kotlin 代码?

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

I feel that is a dumb question, but I'm not familiar with lazy initialization and I'm not sure how to search this question, any "lazy theory link" will be welcome also.我觉得这是一个愚蠢的问题,但我不熟悉惰性初始化,我不知道如何搜索这个问题,任何“惰性理论链接”也将受到欢迎。

private SampleLifecycleListener sll;

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

That way it isn't initialized until the getter is called.这样它在调用 getter 之前不会被初始化。

Beginning with Java 8, you can use ConcurrentHashMap#computeIfAbsent() to achieve laziness.从 Java 8 开始,您可以使用ConcurrentHashMap#computeIfAbsent()来实现惰性。 ConcurrentHashMap is thread-safe. 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
    }
}

You can use this like你可以像这样使用

SampleLifecycleListener sll = lazy.getSampleLifecycleListener();

You can call Kotlin lazy from Java if you want to:如果你想,你可以从 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