ClassTag
s (as well as TypeTag
s and WeakTypeTag
s) are for persisting some compile-time information till runtime. You want to do something in reverse direction. You want, having runtime information (clazz: Class[_]
), to do something at compile time (specify type parameter C
of m2
). So ClassTag
s are irrelevant.
You can call compiler at runtime
import scala.tools.reflect.ToolBox
import scala.reflect.runtime.currentMirror
object App {
val tb = currentMirror.mkToolBox()
def m(clazz: Class[_]): Unit = {
tb.eval(tb.parse(s"import App._; m2[${clazz.getName}]"))
}
def m2[C]() : List[C] = {
println("hi")
List.empty
}
def main(args: Array[String]): Unit = {
m(classOf[String]) //hi
}
}
libraryDependencies ++= Seq(
scalaOrganization.value % "scala-reflect" % scalaVersion.value,
scalaOrganization.value % "scala-compiler" % scalaVersion.value,
)