【发布时间】:2016-08-07 10:53:03
【问题描述】:
我想将类型传递给 Scala 中的函数。
问题详解
第一次迭代
我有以下 Java 类(来自外部源):
public class MyComplexType {
public String name;
public int number;
}
和
public class MyGeneric<T> {
public String myName;
public T myValue;
}
在这个例子中,我希望MyComplexType 是MyGeneric 的实际类型;在真正的问题中有几种可能性。
我想使用 Scala 代码反序列化 JSON 字符串,如下所示:
import org.codehaus.jackson.map.ObjectMapper
object GenericExample {
def main(args: Array[String]) {
val jsonString = "{\"myName\":\"myNumber\",\"myValue\":{\"name\":\"fifteen\",\"number\":\"15\"}}"
val objectMapper = new ObjectMapper()
val myGeneric: MyGeneric[MyComplexType] = objectMapper.readValue(jsonString, classOf[MyGeneric[MyComplexType]])
val myComplexType: MyComplexType = myGeneric.myValue
}
}
编译正常但出现运行时错误:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to MyComplexType
at GenericExample$.main(GenericExample.scala:9)
第二次迭代
问题的有效解决方案:
val jsonString = "{\"myName\":\"myNumber\",\"myValue\":{\"name\":\"fifteen\",\"number\":\"15\"}}"
val objectMapper = new ObjectMapper()
val myGeneric: MyGeneric[MyComplexType] = objectMapper.readValue(jsonString, classOf[MyGeneric[MyComplexType]])
myGeneric.myValue = objectMapper.readValue(objectMapper.readTree(jsonString).get("myValue").toString, classOf[MyComplexType])
val myComplexType: MyComplexType = myGeneric.myValue
不好但有效。 (如果有人知道如何让它变得更好,那也欢迎。)
第三次迭代
第二次迭代解决方案中的行在实际问题中多次出现,因此我想创建一个函数。更改变量是 JSON 格式的字符串和 MyComplexType。
我想要这样的东西:
def main(args: Array[String]) {
val jsonString = "{\"myName\":\"myNumber\",\"myValue\":{\"name\":\"fifteen\",\"number\":\"15\"}}"
val myGeneric = extractMyGeneric[MyComplexType](jsonString)
val myComplexType: MyComplexType = myGeneric.myValue
}
private def extractMyGeneric[T](jsonString: String) = {
val objectMapper = new ObjectMapper()
val myGeneric = objectMapper.readValue(jsonString, classOf[MyGeneric[T]])
myGeneric.myValue = objectMapper.readValue(objectMapper.readTree(jsonString).get("myValue").toString, classOf[T])
myGeneric
}
这不起作用(编译器错误)。我已经玩过Class、ClassTag、classOf 的各种组合,但它们都没有帮助。还有编译器和运行时错误。你知道如何在 Scala 中传递和使用这样的类型吗?谢谢!
【问题讨论】:
标签: java json scala generics reflection