Get Scala Type for a java.lang.Class[T] in Scala 2

2019-03-21 16:28发布

问题:

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)?

回答1:

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
}