从 Java 访问嵌套在伴随对象中的 Kotlin 对象

Accessing a Kotlin object nested in companion object from Java

我在 Kotlin 中有这样的结构

companion object Constants {
    /**
     * Collection of fields and values relative to phone books.
     */
    object PhoneBooks {
        /**
         * Field indicating the ID of a phone book.
         * Each phone book must have an unique ID.
         */
        const val PB_ID_KEY = "PB_ID"

        /**
         * Field indicating the status of phone book.
         */
        const val PB_STATUS_KEY = "PB_Status"

        /**
         * One of the possible [PB_STATUS_KEY] values, when the phone book is in indexing state
         * (usually at startup or in update phase).
         */
        const val PB_INDEXING = "Indexing"
        [...]

问题是我必须有可能从 Java 访问子对象中的常量值,但似乎不可能。如何在不改变结构的情况下解决这个问题?

在上面的评论中,JB Nizet 展示了如何使用静态导入解决问题

但是查看提供的代码我会使用枚举

// kotlin
enum class PhoneBooks(val param:String) {
    PB_ID_KEY("PB_ID"),
    PB_STATUS_KEY("PB_Status"),
    PB_INDEXING("Indexing")

}

// java
System.out.println(PhoneBooks.PB_ID_KEY.getParam());

这里的一大优势是代码可读性 PhoneBooks.PB_ID_KEY 以干净的方式将 PB_ID_KEY 标记为 phone 书籍常量

像 Kotlin sealed 类 kolin 编译器添加了一些很好的枚举检查(详尽的)并且它们被设计 为模式匹配提供清晰可读的代码

在这里查看@Rolands 的回答

评论:

Works fine here using

import static com.yourcompany.yourproject.YourClass.Constants.PhoneBooks;

and then

PhoneBooks.PB_ID_KEY

对我来说效果很好!所以我认为将其作为答案显示是有用的。

尝试使用界面 :)

  companion object Constants {
/**
 * Collection of fields and values relative to phone books.
 */
interface PhoneBooks {
    /**
     * Field indicating the ID of a phone book.
     * Each phone book must have an unique ID.
     */
    const val PB_ID_KEY = "PB_ID"

    /**
     * Field indicating the status of phone book.
     */
    const val PB_STATUS_KEY = "PB_Status"

    /**
     * One of the possible [PB_STATUS_KEY] values, when the phone book is in indexing state
     * (usually at startup or in update phase).
     */
    const val PB_INDEXING = "Indexing"
    [...]