Scala从字符串表示中获取类类型 [英] Scala Getting class type from string representation

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

问题描述

我有一个类名字符串表示

I have a class name string representation

val cls = Class.forName("clsName")
def fromJson[T: Manifest](me: String): T = {
Extraction.extract[T](net.liftweb.json.parse(me))
}

我想将其用作 T:manifest 即

I would like to use it as T:manifest i.e

JsonConverter.fromJson[cls.type](stringData)

返回错误

也试过

val t = Manifest.classType(cls)
JsonConverter.fromJson[t](stringData) // compile error 

最好的方法是什么?有没有办法避免使用反射?

what is the best way to it ? is there a way to avoid using reflection ?

推荐答案

你可以试试这样的:

val cls = Class.forName(myClassName)
val m = Manifest.classType(cls)
val myObj:Any = JsonConverter.fromJson(stringData)(m) 

此方法的一个细微差别是您必须将对象显式键入为 Any.这是因为您没有将类作为编译时,并且对 classType 的调用未提供其类型参数,因此返回的 ManifestManifest[Nothing].不理想,但有效.

One nuance to this approach is that you have to explicitly type the object as an Any. This is because you don't have the class as compile time and the call to classType is not supplied its type param so the Manifest returned is Manifest[Nothing]. Not ideal, but it works.

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

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