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
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 )