在 Kotlin 中获取变量的类型
Get type of a variable in Kotlin
如何在 Kotlin 中找到变量类型?
Java中有instanceof
,但Kotlin不存在:
val properties = System.getProperties() // Which type?
您可以使用 is
operator 检查对象是否属于特定类型:
val number = 5
if(number is Int) {
println("number is of type Int")
}
您还可以使用反射获得 String
类型:
println("${number::class.simpleName}") // "Int"
println("${number::class.qualifiedName}") // "kotlin.Int"
请注意:
On the Java platform, the runtime component required for using the
reflection features is distributed as a separate JAR file
(kotlin-reflect.jar). This is done to reduce the required size of the
runtime library for applications that do not use reflection features.
If you do use reflection, please make sure that the .jar file is added
to the classpath of your project.
来源:https://kotlinlang.org/docs/reference/reflection.html#bound-class-references-since-11
您可以通过 properties::class.simpleName
获得 class 名称
你可以这样使用:
val value="value"
println(value::class.java.typeName)
如何在 Kotlin 中找到变量类型?
Java中有instanceof
,但Kotlin不存在:
val properties = System.getProperties() // Which type?
您可以使用 is
operator 检查对象是否属于特定类型:
val number = 5
if(number is Int) {
println("number is of type Int")
}
您还可以使用反射获得 String
类型:
println("${number::class.simpleName}") // "Int"
println("${number::class.qualifiedName}") // "kotlin.Int"
请注意:
On the Java platform, the runtime component required for using the reflection features is distributed as a separate JAR file (kotlin-reflect.jar). This is done to reduce the required size of the runtime library for applications that do not use reflection features. If you do use reflection, please make sure that the .jar file is added to the classpath of your project.
来源:https://kotlinlang.org/docs/reference/reflection.html#bound-class-references-since-11
您可以通过 properties::class.simpleName
你可以这样使用:
val value="value"
println(value::class.java.typeName)