在转换/编译期间,JVM 在什么时间计算伴随对象的值?

What time during translation/compilation JVM computes the value for a companion object?

提问人:Роман Сущенко 提问时间:11/9/2023 更新时间:11/9/2023 访问量:25

问:

我正在 MacOS 上使用 Kotlin 1.9.20

enum class Enum {
    SOME_VALUE;

    companion object {
        private val ENV: String = System.getProperty("ENVIRONMENT")
    }
}

我试图为包含伴随对象的枚举编写一个测试,但它始终失败,说 ENV 为 null。

我尝试在测试中使用@BeforeAll来设置系统属性,但它没有帮助,函数仍然返回null

    companion object {
        @JvmStatic
        @BeforeAll
        fun setUp(): Unit {
            System.setProperty(ServerEnv.ENV_PROPERTY, "junit")
        }
    }

我怀疑 Kotlin 在编译为字节码期间评估了伴随对象的值,但我没有在任何地方找到任何确认,包括文档,请帮助我!

Kotlin OOP 编译 JVM

评论


答: 暂无答案