Skip to content

[3] Mapper

Sven Braune edited this page Mar 26, 2021 · 2 revisions

@Mapper Annotation

Can be used to convert object states of complex classes into a map representation and back. That way it's possible to persist a current application-state to make it restorable after a restart

How to use

Add dependencies and base configurations

Check General Setup

Annotate Class

@Mapper
class DummyMapperSource(simple: String = "test123") {

   @Mapify
   private val myPrivateValWithAVeryVeryVeryVeryLongName: String? = simple

   @Mapify
   var innerObject: MyMapifyableTest = MyMapifyableTest(simple)

   @Mapify
   var innerObjectList: List<MyMapifyableTest> = listOf(MyMapifyableTest(simple))

   @Mapify
   var innerObjectMap: Map<String, MyMapifyableTest> = mapOf("test" to MyMapifyableTest(simple))

   @Mapify
   var testSerializable: TestSerializable = TestSerializable(simple, 5)

   @Mapify(nullableIndexes = [0])
   var product: ProductEntity? = null

   @Mapify
   var booleanValue: Boolean = true

   @Mapify(nullableIndexes = [0])
   var bigDecimalValue: BigDecimal? = null

   @Mapify(nullableIndexes = [1])
   var nullableList : MutableList<String?> = mutableListOf(null)

   @Mapify(nullableIndexes = [1, 2])
   private val nullableMap : Map<String?, Int?> = mapOf()

   @Mapify
   val mapper: InnerMapperSource<TestSerializable?, String> = InnerMapperSource(TestSerializable(simple, 5), simple)

   @Mapify
   val liveData = ExposingSource<String>()


   val privateValExpose
       get() = myPrivateValWithAVeryVeryVeryVeryLongName

   data class TestSerializable(val test1: String, val test2: Int) : Serializable

   @Mapifyable(MyMapifyableTest.Mapper::class)
   class MyMapifyableTest(val myString: String) {

       class Mapper : IMapifyable<MyMapifyableTest> {
           override fun fromMap(map: Map<String, Any>): MyMapifyableTest {
               return MyMapifyableTest(map["test"] as String)
           }

           override fun toMap(obj: MyMapifyableTest): Map<String, Any> {
               return mapOf("test" to obj.myString)
           }

       }
   }

Build your Project

  // This is generated by the Annotation Processor
  val mapper = DummyMapperSourceMapper()
  val oldObj = DummyMapperSource("oldValue")

  // Save obj to Map
  val mapToPersist = mapper.toMap(oldObj)

  val newObj = DummyMapperSource("newValue")
  // restore obj
  mapper.fromMap(newObj, mapToPersist)

  // great :)
  assertEquals("oldValue", privateValExpose)

The Framework can work with the following data types:

  • Plain (String, Boolean, Double, Integer, BigDecimal, ...)
  • Serializable
  • Lists
  • Maps
  • @Mapifyable annotated classes
  • @Mapper annotated classes

It's also possible to work with type-params or nullables only rule the implementation of the type params needs to match the types above

Clone this wiki locally