kotlin reflection get list of fields

后端 未结 4 2285
情书的邮戳
情书的邮戳 2021-02-18 20:51

is there an equivalent for the java reflection foo.getClass().getFields() in Kotlin? I could only find that I can access a field when I know it\'s name, but I would

4条回答
  •  长发绾君心
    2021-02-18 21:28

    There is a method in Kotlin that works without having to add a new dependency in a project:

    Suppose a custom class called Mine

    class Mine(var prop:String) {
        fun myMethod():Boolean {
            return true
        }
    }
    

    A new user function called isMethod

    fun isMethod(t:Any, s:String):Boolean {
    try  {
        t.javaClass.getMethod(s)   // or t::class.java.getMethod(s)
        return true
      } catch(e:Exception)  {
        return false
      }    
    }
    

    After one declares an Mine instance and test it.

    fun main() {
      var m = Mine("Paulo")  
      println(isMethod(m, "myMethod"))  // it prints true
      println(isMethod(m, "otherMethod"))  // it prints false
    }
    

提交回复
热议问题