从类名字符串中获取TypeTag

mon*_*ack 2 reflection scala

简单的问题,如何TypeTag从类名获得?

所以基本上TypeTag相当于Class.forNameJava.

注意:Manifest不会在这里为我做,我需要一个TypeTag.虽然如果有一种方法可以从清单转到typetag,那也可以,因为我可以从类名中获取清单.

Vla*_*eev 11

Manifest已弃用,可能会在将来的Scala版本中消失.我认为依靠它们并不明智.您只能使用新的Scala反射来执行您想要的操作.

您可以从一个字符串去Class得到它的类加载器,然后就可以创建一个TypeTagClass通过一面镜子,在概述这个答案.这是一段稍微改编的代码,展示了它:

import scala.reflect.runtime.universe._
import scala.reflect.api

def stringToTypeTag[A](name: String): TypeTag[A] = {
  val c = Class.forName(name)  // obtain java.lang.Class object from a string
  val mirror = runtimeMirror(c.getClassLoader)  // obtain runtime mirror
  val sym = mirror.staticClass(name)  // obtain class symbol for `c`
  val tpe = sym.selfType  // obtain type object for `c`
  // create a type tag which contains above type object
  TypeTag(mirror, new api.TypeCreator {
    def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =
      if (m eq mirror) tpe.asInstanceOf[U # Type]
      else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
  })
}
Run Code Online (Sandbox Code Playgroud)