什么相当于Kotlin"懒惰"在Java?

时间:2018-04-19 16:16:49

标签: java android kotlin

我跟着这篇文章https://proandroiddev.com/detecting-when-an-android-app-backgrounds-in-2018-4b5a94977d5c来实现android生命周期,但是在java上有Application类的遗留应用上。

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

<?xml version="1.0" encoding="UTF-8"?>
<server description="new server">

    <!-- Enable features -->
    <featureManager>
        <feature>jsp-2.2</feature>
    </featureManager>
    <featureManager>
      <feature>adminCenter-1.0</feature>
    </featureManager>

   <!-- Define the host name for use by the collective.
        If the host name needs to be changed, the server should be
        removed from the collective and re-joined. -->
   <variable name="defaultHostName" value="localhost" />

    <!-- Define an Administrator and non-Administrator -->
   <basicRegistry id="basic">
      <user name="admin" password="********" />
      <user name="nonadmin" password="***********" />
   </basicRegistry>

   <!-- Assign 'admin' to Administrator -->
   <administrator-role>
      <user>admin</user>
   </administrator-role>

   <keyStore id="defaultKeyStore" password="*******" />

    <!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
    <httpEndpoint id="defaultHttpEndpoint"
                  host="*"
                  httpPort="9080"
                  httpsPort="9443" />

        <!-- Automatically expand WAR files and EAR files -->
        <applicationManager autoExpand="false"/>
</server>

我觉得这是一个愚蠢的问题,但我不熟悉懒惰的初始化,我不知道如何搜索这个问题,任何&#34;懒惰的理论链接&#34;也欢迎。

3 个答案:

答案 0 :(得分:7)

private SampleLifecycleListener sll;

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

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

答案 1 :(得分:2)

从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();

答案 2 :(得分:0)

如果愿意,可以从Java调用Kotlin lazy

import kotlin.Lazy;

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