Using scala 2.10, I am trying to instantiate a class from a string and I would like to get its typetag.
for example :
scala> def printClassName[Y: TypeTag](x: Y) = { println(typeTag[Y].tpe) }
printClassName: [Y](x: Y)(implicit evidence$1: reflect.runtime.universe.TypeTag[Y])Unit
this is working :
scala> printClassName(new String())
String
But this is not :
scala> var foo = Class.forName("java.lang.String")
myInstance: Class[_] = class java.lang.String
scala> printClassName(foo)
java.lang.Class[?0]
Is there a way to overcome java erasure at runtime with scala ?
A TypeTag is completely compiler-generated, that means that the compiler creates and fills in a TypeTag when one calls a method expecting such a TypeTag . There exist three different forms of tags: scala. reflect. ClassTag.
A ClassTag[T] stores the erased class of a given type T , accessible via the runtimeClass field. This is particularly useful for instantiating Array s whose element types are unknown at compile time. ClassTag s are a weaker special case of scala. reflect. api.
Type erasure refers to the runtime encoding of parameterized classes in Scala. It is simply performed by Scala compiler in which it removes all the generic type information after compilation. In Scala, generics are erased at runtime, which means that the runtime type of List[Int] and List[Boolean] is actually the same.
A Manifest[T] is an opaque descriptor for type T. Its supported use is to give access to the erasure of the type as a Class instance, as is necessary for the creation of native Arrays if the class is not known at compile time.
I believe you can use the Scala Reflection api to get the Type
(not TypeTag
). Not sure if this is what you wanted but it is the same thing being printed in typeTag[Y].tpe
.
import scala.reflect.runtime.universe._
val m = runtimeMirror(getClass.getClassLoader)
val classSymbol = m.staticClass("java.lang.String")
val tpe = classSymbol.selfType
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With