I'd like to experiment with the use of a dynamic data model with a reflective library that uses typeOf[]
.
I've defined a class at runtime with a Scala reflection ToolBox
in 2.11:
import scala.tools.reflect.ToolBox
import scala.reflect.runtime.universe._
import scala.reflect.runtime.{ currentMirror => cm }
def cdef() = q"case class C(v: String)"
val tb = cm.mkToolBox()
val csym = tb.define(cdef())
def newc(csym: Symbol) = q"""new ${csym}("hi")"""
val obj = tb.eval(newc(csym))
I'm able to circumvent the typeOf[]
call by entering Scala reflection via the ClassSymbol
instead, but that requires modifying a library over which I have no immediate control.
Is there any way that I can use it as a type parameter in a library whose entry point is typeOf[]
?
I've tried:
The only way I found to go from a value to something that I could use in the type position was use Java reflection to invoke the companion class' apply method and call .type
on the result:
val method_apply = obj.getClass.getMethod("apply", "".getClass)
val typeTemplate = method_apply.invoke(obj, "hello")
type MyType = typeTemplate.type
(Keeping with the naming scheme of @xeno_by and @travisbrown 's menagerie of odd types, I might call this "Frankenstein's Type", because it is made from parts, given life at the wrong time, not quite a substitute for the original, and given that this is all happening at runtime, should probably be burned with fire.)
This type alias works as a type parameter is some cases. But in the case of typeOf[MyType]
, the the compiler makes a TypeTag
before the runtime type is defined, so typeOf[MyType]
returns a type member that doesn't correspond to the runtime type/class (e.g. TypeTag[package.Example.MyType]
instead of TypeTag[package.C]
)
Should I expect the ToolBox
to have generated a TypeTag
, and if so, how do I use it?
If I have to make a TypeTag
at runtime, this question shows me how, but then how do I attach it to whatever I use as a type parameter?
Thanks for any ideas,
-Julian