0

In my android project I'm trying to loop through all the fields of a class using reflection, however, the result of declaredFields includes two unexpected fields, $change and serialVersionUID which aren't defined in the class

This is in an android project using a Kotlin data class. I've tried looking up the two fields in question and have seen that serialVersionUID seems to relate to classes which extend serialisable (https://stackoverflow.com/a/285809/8023278), the class in question doesn't implement serialisable though and I can't find any details about $change.

data class MyClass(
        @field:Json(name = "Id") var id: String
)

// then in some other class/method
MyClass::class.java.declaredFields.forEach { 
  // do something. 
  Log.d("", it.name)
}

I would expect only id to be logged however I actually get id, $change and serialVersionUID.

Rex5
  • 771
  • 9
  • 23
Matt Smith
  • 836
  • 10
  • 21

1 Answers1

0

Answering my own question for anyone that encounters this in the future.

The extra fields seem to be added by instant run, disabling instant run fixed the problem. I have instant run disabled on my machine and wasn't seeing the two extra fields however my colleagues had instant run enabled and were all getting both $change and serialVersionUID.

Another solution I found was to filter out these fields. $change appears to be synthetic so can check against isSynthetic(). What I ended up actually doing was checking if the kotlin property of the field was null which it is for these two fields and not the classes actual fields.

MyClass::class.java.declaredFields.filter { it.kotlinProperty != null }.forEach {
 // ...
}
Matt Smith
  • 836
  • 10
  • 21