如何从 kotlin 中的伴随对象访问外部 class' javaClass.simpleName?

how to access outer class' javaClass.simpleName from companion object in kotlin?

我希望能够从它的伴随对象访问我的 class 的 simpleName。

我想要这个:

val o1 = Outer("foo")
val o2 = Outer("bar")

打印以下输出:

Outer: hello
Outer: foo
Outer: bar

实际用例是 java:

class Outer {
    static final String TAG = Outer.class.simpleName();
    // and now I'm able to use Outer.TAG or just TAG in both static and non-static methods
}

我尝试了两件事:

  1. 将 Outer 的 simpleName 分配给伴生对象的 COMPANION_TAG,然后使用伴生对象的 init 和 Outer 的所有函数中的 COMPANION_TAG。我可以从我需要的任何地方访问 COMPANION_TAG,但不幸的是我只能通过这种方式获得 "Companion" 而不是 "Outer"。

  2. 从伴随对象的 init 访问 Outer.OUTER_TAG。这里的问题是我找不到访问它的方法。

代码如下:

class Outer(str: String) {
    private val OUTER_TAG = javaClass.simpleName
    companion object {
        @JvmStatic val COMPANION_TAG = PullDownAnimationLayout.javaClass.simpleName // gives "Companion" :(
        init {
            // how can I access OUTER_TAG?
            Log.d(OUTER_TAG, "hello") // this gives an error
        }
    }
    init {
        Log.d(OUTER_TAG, str) // Outer: ... :)
        Log.d(INNER_TAG, str) // Companion: ... :(
    }
}

val o1 = Outer()
val o2 = Outer()

为了在 Kotlin 中实现这一点,

class Outer {
    static final String TAG = Outer.class.simpleName();
    // and now I'm able to use Outer.TAG or just TAG in both static and non-static methods
}

应该是

class Outer {
    companion object {
        val Tag = Outer::class.java.simpleName
        val Tag2 = Outer.javaClass.simpleName // This will not work
    }
}

println(Outer.Tag)  // print Outer
println(Outer.Tag2) // print Companion

我认为您误解了 companion 是什么。 companion 类似于 Java 静态。看到这个 discussion.