本文介绍了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 的调用未提供其类型参数,因此返回的 Manifest 是 Manifest[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从字符串表示中获取类类型
发布评论