我有一些代码将json字符串转换为如下对象:
def apply(line: String): PairEvent = {
val (name, json) = line.span(_ != ' ')
name match {
case "OpenTabEvent" => Serialization.read[OpenTabEvent](json)
case "CloseTabEvent" => Serialization.read[CloseTabEvent](json)
case "ChangeContentEvent" => Serialization.read[ChangeContentEvent](json)
case "ChangeMasterRequest" => Serialization.read[ChangeMasterRequest](json)
case "CreateFileEvent" => Serialization.read[CreateFileEvent](json)
case "DeleteFileEvent" => Serialization.read[DeleteFileEvent](json)
case "CreateDirEvent" => Serialization.read[CreateDirEvent](json)
case "DeleteDirEvent" => Serialization.read[DeleteDirEvent](json)
case "WatchingFiles" => Serialization.read[WatchingFiles](json)
case _ =>
ServerLogger.info("!!!!!!!!!!!!!!!!!!!!! unknown line from server: " + line)
???
}
}
你可以看到我硬编码了一些字符串并将它们用作转换为对象的类型。
有没有办法在没有硬编码的情况下做同样的事情?我不确定它是否可能,即使是宏。
答案 0 :(得分:0)
您可以使用班级名称:
case OpenTabEvent.getClass.getSimpleName => Serialization.read[OpenTabEvent](json)