Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the typeTag of a runtime instance?

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 ?

like image 721
itsu Avatar asked May 23 '13 21:05

itsu


People also ask

What is TypeTag?

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.

What is ClassTag in Scala?

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.

What is Scala type erasure?

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.

What is manifest in Scala?

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.


1 Answers

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
like image 77
cmbaxter Avatar answered Nov 15 '22 09:11

cmbaxter