【问题标题】:Scala Getting class type from string representationScala从字符串表示中获取类类型
【发布时间】:2023-03-13 22:22:01
【问题描述】:

我有一个类名字符串表示

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

我想用它作为 T:manifest 即

JsonConverter.fromJson[cls.type](stringData)

这会返回一个错误

也试过了

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

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

【问题讨论】:

    标签: scala serialization


    【解决方案1】:

    你可以试试这样的:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-16
      • 1970-01-01
      • 2011-01-25
      • 2010-10-17
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多