mardi 19 février 2019

Compensating for Type Erasure

I'm writing a serialization library that needs to compensate for type erasure. See example class to be serialized below:

trait Body
case class AnyBody(stuff: Any, count: Int) extends Body

case class Envelope1[T <: Body](id: String, body: T) {
  type Giraffe = T
}

The convention using a named type member (Giraffe) will generate serialized output having a type hint Giraffe with value of the actual type of T, e.g. AnyBody.

This actually works well for simple values of T:

{"Giraffe":"com.foo.Anybody", "id":"abc123", "body":{"stuff":15, "count":2}}

This scheme falls apart if wrapped types like containers, Option, or Try are involved.

case class Envelope2[T <: Body](id: String, body: Option[T]) {
  type Giraffe = T
}

Reflection only tells me body is a Some/None but seems to have erased the actual type of AnyBody.

Is there an alternate approach (annotations?) that will clue my serializer as to the actual wrapped type at runtime? If annotations, how can I get the actual type for T in the annotation so it can be read by the serializer?





Aucun commentaire:

Enregistrer un commentaire