【问题标题】:How to check "instanceof " class in kotlin?如何在 kotlin 中检查“instanceof”类?
【发布时间】:2017-10-21 06:43:06
【问题描述】:

在 kotlin 类中,我将方法参数作为对象(参见 kotlin doc here),用于类类型 T。作为对象,我在调用方法时传递了不同的类。 在 Java 中,我们可以使用对象的instanceof 来比较类是哪个类。

所以我想在运行时检查和比较它是哪个类?

如何在 kotlin 中查看 instanceof 类?

【问题讨论】:

    标签: kotlin kotlin-extension


    【解决方案1】:

    使用is

    if (myInstance is String) { ... }
    

    或相反!is

    if (myInstance !is String) { ... }
    

    【讨论】:

    • 这仅适用于从 Kotlin 类创建实例对象时。如果实例是使用来自 SomeClass::class.java 之类的 newInstance() 创建的,这将不起作用
    • @androiddev 为什么会这样?
    • 不知道。我试过了,但它不起作用。 Kotlin 与 Java 交互的方式有些奇怪。但是,您可以使用 SomeClass.isInstance(someObject),它确实有效。
    【解决方案2】:

    结合whenis

    when (x) {
        is Int -> print(x + 1)
        is String -> print(x.length + 1)
        is IntArray -> print(x.sum())
    }
    

    复制自official documentation

    【讨论】:

    • 是的,这是惯用的方式。
    【解决方案3】:

    我们可以通过使用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")
    }
    

    【讨论】:

    • 请注意另一件好事:在if 的块内,obj 自动转换为String。所以你可以直接使用length等属性,而不需要在块内显式地将obj转换为String
    • 另外,使用 else 语句的好机会 ;)
    • 如果我想区分两个类,其中一个扩展另一个类,例如 LinearLayoutManager 和 GridLayoutManager
    【解决方案4】:

    你可以使用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 */ }
    }
    

    【讨论】:

      【解决方案5】:

      尝试使用名为is 的关键字 Official page reference

      if (obj is String) {
          // obj is a String
      }
      if (obj !is String) {
          // // obj is not a String
      }
      

      【讨论】:

      • 用官方文档给出答案真是太好了。但是在答案中添加示例代码是更好的做法,如果链接失效,这会很有帮助。感谢您的回答。
      【解决方案6】:

      您可以在 https://kotlinlang.org/docs/reference/typecasts.html 阅读 Kotlin 文档。我们可以通过使用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
      

      【讨论】:

        【解决方案7】:

        你可以这样检查

         private var mActivity : Activity? = null
        

        然后

         override fun onAttach(context: Context?) {
            super.onAttach(context)
        
            if (context is MainActivity){
                mActivity = context
            }
        
        }
        

        【讨论】:

          【解决方案8】:

          您可以将任何类与以下函数进行比较。

          fun<T> Any.instanceOf(compared: Class<T>): Boolean {
              return this::class.java == compared
          }
          
          // When you use
          if("test".isInstanceOf(String.class)) {
              // do something
          }
          

          【讨论】:

            【解决方案9】:

            其他解决方案:KOTLIN

            val fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
            
            if (fragment?.tag == "MyFragment")
            {}
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2022-07-22
              • 2021-12-21
              • 2016-06-14
              • 1970-01-01
              • 2017-01-03
              相关资源
              最近更新 更多