kotlin reflection get list of fields

后端 未结 4 2284
情书的邮戳
情书的邮戳 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:26

    You can't do this in Kotlin, but there is a dirty unreliable way to do this in java. You can use java reflection. Like this:

    public class TestClass {
    
        trait EmptyTrait
        class EmptyClass
    
        public var anotherVar:Int? = null
        public val contant:Float = 10f
        private var emptyTrait:EmptyTrait? = null
        val emptyClass:EmptyClass = EmptyClass()
    
        public fun setVal(fieldName: String, value: Int) {
            javaClass.getDeclaredField(fieldName).set(this, value);
        }
    
        public fun getFieldNames(): String {
            return javaClass.getDeclaredFields().map{it.getName()}.join(", ")
        }    
    }
    

    Let's test it:

    val t = TestClass()
    Log.v("MainActivity", "Fields: " + t.getFieldNames())
    Log.v("MainActivity", "anotherVar: " + t.anotherVar)
    t.setVal("anotherVar", 10)
    Log.v("MainActivity", "anotherVar: " + t.anotherVar)
    

    Results:

    Fields: anotherVar, emptyClass, emptyTrait, contant, $kotlinClass
    anotherVar: null
    anotherVar: 10
    

    it works )

提交回复
热议问题