Java Kotlin:相当于 KClass 的 getClass()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32655216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:55:47  来源:igfitidea点击:

Kotlin: Equivalent of getClass() for KClass

javaclasskotlin

提问by Jire

In Java we can resolve a variable's class through getClass()like something.getClass(). In Kotlin I am aware of something.javaClasswhich is nice but I want to be able to get the KClassin a similar way. I've seen the Something::classsyntax but this is not what I need. I need to get the KClass of a variable. Does such functionality exist?

在 Java 中,我们可以通过getClass()like解析变量的类something.getClass()。在 Kotlin 中,我知道something.javaClass哪个很好,但我希望能够以KClass类似的方式获得。我看过Something::class语法,但这不是我需要的。我需要获取变量的 KClass。是否存在这样的功能?

采纳答案by Alexander Udalov

The easiest way to achieve this since Kotlin 1.1 is the class reference syntax:

自 Kotlin 1.1 以来,实现这一目标的最简单方法是类引用语法

something::class

If you use Kotlin 1.0, you can convert the obtained Java class to a KClass instance by calling the .kotlinextension property:

如果使用 Kotlin 1.0,则可以通过调用.kotlin扩展属性将获取的 Java 类转换为 KClass 实例:

something.javaClass.kotlin

回答by dherman

EDIT: See comments, below, and answer from Alexander, above. This advice was originally for Kotlin 1.0 and it seems is now obsolete.

编辑:请参阅下面的评论和上面亚历山大的回答。这个建议最初是针对 Kotlin 1.0 的,现在似乎已经过时了。

Since the language doesn't support a direct way to get this yet, consider defining an extension method for now.

由于该语言尚不支持直接获取此方法,因此现在考虑定义扩展方法

fun<T: Any> T.getClass(): KClass<T> {
    return javaClass.kotlin
}

val test = 0
println("Kotlin type: ${test.getClass()}")

Or, if you prefer a property:

或者,如果您更喜欢房产:

val<T: Any> T.kClass: KClass<T>
    get() = javaClass.kotlin

val test = 0
println("Kotlin type: ${test.kClass}")

回答by Kashif Anwaar

Here's my solution

这是我的解决方案

val TAG = javaClass.simpleName

With javaClass.simpleName you can obtain your class name. Also the above example is very useful for android developers to declare on top of the class as an instance variable for logging purposes.

使用 javaClass.simpleName 您可以获得您的类名。此外,上面的示例对于 android 开发人员在类的顶部声明为用于日志记录目的的实例变量非常有用。