samedi 27 juillet 2019

Kotlin data class instanciation via reflection

I am writing a small data access layer for our application connecting to MongoDB and I want to initialize queried entities to (domain model) data classes automatically using reflection

I have seen people talking about JSON deserialization to Kotlin data classes and I see why that would be an option due to MongoDB returning data in the related BSON format. However, I want to abstract over that data source.

So given a map of field names and values of arbitrary type, how can I define a function toDomain so that it takes such a map and the target class Class<T> as parameters and spits out a T as result? I am stuck because the newInstance() method invokes the (nonexistent) default constructor and the arity and types of my data class constructor arguments vary so I can't "hardcode" this information either.

Edit: I want to clarify that I do not want to know about any libraries I can simply plug into my code (except if they are open source and have a readable implementation) but instead I want to learn about the possibilities I have with reflections in this hindsight.





Aucun commentaire:

Enregistrer un commentaire