mardi 20 février 2018

Scala reflection Generic TypeArgs exposure

I seem to be stuck behind generic type parameters when trying to expose the case accessors in a case class via reflect.

Say I have this:

case class test(
  propA: Option[Int],
  propB: String
)

I can spit out the model of the test case class but am stuck with this result:

{ "subject" : "test",
  "model" : [
    {"field" : "propA", "type" : "A"},
    {"field" : "propB", "type" : "String"}
  ]
}

The entries come in as java Fields and I'm using the runtimeMirror to get a ClassSymbol for the class as provided via Field.getType.

val parameterizedType = runtimeMirror(field.getType.getClassLoader).classSymbol(field.getType)

Then I'm trying to use the selfType to get at the typeArgs but as shown above instead of getting Int I'm getting A and it has me stuck because I'm not as familiar with scala reflect. The type exposure is done with the following line:

parameterizedType.selfType.dealias.typeArgs.map(_.toString).mkString

I tried to use only Scala reflect to expose the field but the class that I'm inspecting is sometimes a Java class and I ran into issues exposing the fields that way.

Additionally, I've been able to expose the full type path but it still hides the parameterized type:

... "propA", "type" : "scala.Option.A"

Any help is appreciated!





Aucun commentaire:

Enregistrer un commentaire