从类名字符串中获取 TypeTag [英] Getting TypeTag from a classname string

查看:50
本文介绍了从类名字符串中获取 TypeTag的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,如何从类名中获取TypeTag?

Simple question, how does one get a TypeTag from a classname?

所以基本上 TypeTag 相当于 Java 中的 Class.forName.

So basically the TypeTag equivalent of Class.forName in Java.

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

Note: Manifest won't do for me here, I need a TypeTag. Although if there's a way to go from a manifest to a typetag, that would work too, as I can get a Manifest from the classname.

推荐答案

您可以使用 Class.forNameString 获取 Class>, ManifestFactory.classTypeClass 获取一个 Manifest,然后 scala.reflect.runtime.universe.manifestToTypeTag 得到一个 TypeTag:

You can use Class.forName to get a Class from a String, ManifestFactory.classType to get a Manifest from the Class, and then scala.reflect.runtime.universe.manifestToTypeTag to get a TypeTag:

import scala.reflect.runtime.universe
import scala.reflect.ManifestFactory

val className = "java.lang.String"
val mirror = universe.runtimeMirror(getClass.getClassLoader)
val cls = Class.forName(className)
val t = universe.manifestToTypeTag(mirror,
                                   ManifestFactory.classType(cls))

这篇关于从类名字符串中获取 TypeTag的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆