在 kotlin 类中,我将方法参数作为类类型T的对象(参见 kotlin doc here ) 。作为对象,我在调用方法时传递了不同的类。在Java中,我们可以使用对象来比较类是哪个类。instanceof
所以我想在运行时检查和比较它是哪个类?
如何instanceof
在 kotlin 中查看课程?
在 kotlin 类中,我将方法参数作为类类型T的对象(参见 kotlin doc here ) 。作为对象,我在调用方法时传递了不同的类。在Java中,我们可以使用对象来比较类是哪个类。instanceof
所以我想在运行时检查和比较它是哪个类?
如何instanceof
在 kotlin 中查看课程?
使用is
.
if (myInstance is String) { ... }
或相反!is
if (myInstance !is String) { ... }
结合when
和is
:
when (x) {
is Int -> print(x + 1)
is String -> print(x.length + 1)
is IntArray -> print(x.sum())
}
复制自官方文档
is
我们可以通过使用运算符或其否定形式在运行时检查对象是否符合给定类型!is
。
例子:
if (obj is String) {
print(obj.length)
}
if (obj !is String) {
print("Not a String")
}
自定义对象的另一个示例:
让,我有一个obj
类型CustomObject
。
if (obj is CustomObject) {
print("obj is of type CustomObject")
}
if (obj !is CustomObject) {
print("obj is not of type CustomObject")
}
您可以使用is
:
class B
val a: A = A()
if (a is A) { /* do something */ }
when (a) {
someValue -> { /* do something */ }
is B -> { /* do something */ }
else -> { /* do something */ }
}
尝试使用称为is
官方页面参考的关键字
if (obj is String) {
// obj is a String
}
if (obj !is String) {
// // obj is not a String
}
您可以在此处阅读 Kotlin 文档https://kotlinlang.org/docs/reference/typecasts.html。is
我们可以通过使用运算符或其否定形式在运行时检查对象是否符合给定类型,!is
例如使用is
:
fun <T> getResult(args: T): Int {
if (args is String){ //check if argumen is String
return args.toString().length
}else if (args is Int){ //check if argumen is int
return args.hashCode().times(5)
}
return 0
}
然后在主要功能中,我尝试在终端上打印并显示它:
fun main() {
val stringResult = getResult("Kotlin")
val intResult = getResult(100)
// TODO 2
println(stringResult)
println(intResult)
}
这是输出
6
500
你可以像这样检查
private var mActivity : Activity? = null
然后
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is MainActivity){
mActivity = context
}
}
您可以将任何类与以下功能进行比较。
fun<T> Any.instanceOf(compared: Class<T>): Boolean {
return this::class.java == compared
}
// When you use
if("test".isInstanceOf(String.class)) {
// do something
}
其他解决方案:KOTLIN
val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
if (fragment?.tag == "MyFragment")
{}