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

不羁的心 提交于 2019-12-04 13:56:15

问题


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
}


来源:https://stackoverflow.com/questions/15067872/get-scala-type-for-a-java-lang-classt-in-scala-2-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!