Colton Idle
09/28/2023, 4:45 PM@Serializable
data class Outer(
val innerName: Inner
)
and then I have an instance of this Outer class. How can I do something like this outer.innerName.getSerializedName()
Basically. I need to save the name of the field onto disk. I can do outer.innerName::class.java.simpleName
but that gives me "Inner" instead of what I want which is "innerName".Casey Brooks
09/28/2023, 5:18 PMinnerName
is a property of the Outer
class, not Inner
. So you need to use reflection on Outer::class
instead. outer.innerName
is a reference to an instance of Inner
, so outer.innerName::class.java.simpleName
gives you the class name for Inner
.
For example:
Outer::class.java.declaredFields.map { it.name } // [innerName]
Note that this gives you the Java field name for that property, not necessarily the serial name. If you’re not using any obfuscation or @SerialName
annotations, they should be the same, but it’s not really guaranteed. If you do need the actual serial name, you’ll probably need to write a custom format for persisting that data to disk (which also has the benefit of working on other targets besides JVM)ephemient
09/28/2023, 5:32 PMOuter.serializer().descriptor.getElementName(0)
Colton Idle
09/28/2023, 6:00 PMephemient
09/28/2023, 6:01 PMColton Idle
09/28/2023, 6:11 PM@Serializable
data class Outer(
val innerName: Inner
val fooName: Foo
val barName: Bar
)
and I'm just trying to write a function to get the left side of the :
ephemient
09/28/2023, 6:14 PMfor (i in 0 until descriptor.getElementCount) {
if (descriptor.getElementDescriptor(i) == Inner.serializer().descriptor)
return descriptor.getElementName(i)
but it doesn't provide a mapping between serial name and property name, if that's what you're looking forCasey Brooks
09/28/2023, 6:22 PMephemient
09/28/2023, 6:25 PMfun <T> KClass<T>.serializer()
)