Java Kotlin 获取类型为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32684739/
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:56:42  来源:igfitidea点击:

Kotlin get type as string

javakotlin

提问by Alex Facciorusso

I can't find how to get the type of a variable (or constant) as String, like typeof(variable), with Kotlin language. How to accomplish this?

我找不到如何使用 Kotlin 语言获取变量(或常量)的类型 as String,例如typeof(variable)。如何做到这一点?

采纳答案by Lamorak

You can use one of the methods that best suits your needs:

您可以使用最适合您需求的方法之一:

val obj: Double = 5.0

System.out.println(obj.javaClass.name)                 // double
System.out.println(obj.javaClass.kotlin)               // class kotlin.Double
System.out.println(obj.javaClass.kotlin.qualifiedName) // kotlin.Double

You can fiddle with this here.

你可以在这里摆弄这个。

回答by Rodrigo Gomes

Type Checks and Casts: 'is' and 'as'

类型检查和转换:'is' 和 'as'

if (obj is String) {
  print(obj.length)
}

if (obj !is String) { // same as !(obj is String)
  print("Not a String")
}

回答by Paulo Buchsbaum

There is a simpler way using simpleNameproperty and avoiding Kotlinprefix.

有一种更简单的方法使用simpleName属性并避免Kotlin前缀。

val lis = listOf(1,2,3)

lisis from type ArrayList. So one can use

lis来自类型ArrayList。所以可以使用

println(lis.javaClass.kotlin.simpleName)  // ArrayList

or, more elegantly:

或者,更优雅地:

println(lis::class.simpleName)  // ArrayList