Scala Getting class type from string representation

杀马特。学长 韩版系。学妹 提交于 2019-12-22 14:00:29

问题


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))
}

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

JsonConverter.fromJson[cls.type](stringData)

this returns an error

tried also

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 ?


回答1:


You could try something like this:

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

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.



来源:https://stackoverflow.com/questions/16402413/scala-getting-class-type-from-string-representation

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