4

I was looking at the scala reflection overview and I'm wondering if it is possible to use a java.lang.Class<T> as a Type in Scala 2.10.

import scala.reflect.runtime.{ universe => ru }

class Reflector {
  def getType: ru.Type = {
    ru.typeOf[java.lang.String]
  }
  def getType[T](clazz: Class[T]): ru.Type = {
    //is it possible to implement me?
  }
}

Is it possible to implement the parse[T](clazz: Class[T]): ru.Type method without changing its signature in order to be able to call it from java with new Reflector().parse(String.class)?

Jonas Adler
  • 905
  • 5
  • 9

1 Answers1

8

You could implement your method like this:

def getType[T](clazz: Class[T])(implicit runtimeMirror: ru.Mirror) =
  runtimeMirror.classSymbol(clazz).toType

And then call it like this:

implicit val mirror = ru.runtimeMirror(getClass.getClassLoader)
getType(classOf[String])

You might be interested in the smirror library as it contains a similar method

def sClassOf[T](clazz: Class[T])(implicit runtimeMirror: Mirror): SClass[T]

Where SClass contains a typ property.


Edit

You might want to change the method to this (that would keep the same signature)

def getType[T](clazz: Class[T]):ru.Type = {
  val runtimeMirror =  ru.runtimeMirror(clazz.getClassLoader)
  runtimeMirror.classSymbol(clazz).toType
}
EECOLOR
  • 11,184
  • 3
  • 41
  • 75
  • 1
    I have edited the answer to comply with the 'without changing its signature' requirement of the OP – EECOLOR Feb 25 '13 at 13:51