我有两个嵌套的case类:
case class InnerClass(param1: String, param2: String)
case class OuterClass(myInt: Int, myInner: InnerClass)
val x = OuterClass(11, InnerClass("hello", "world"))
这是我要转换为Map类型的嵌套地图[字符串,任何]让我得到这样的:
Map(myInt -> 11, myInner -> Map(param1 -> hello, param2 -> world))
当然,解决方案应该是通用的,对任何情况下的类工作。
注: 此讨论了关于如何将单例类映射到地图一个很好的答案。 但我无法使它适应巢式病例类。 相反,我得到:
Map(myInt -> 11, myInner -> InnerClass(hello,world)
作为路易吉Plinge在评论指出以上,这是一个非常糟糕的主意 - 你投掷式安全窗外,将有很多丑陋的铸件和运行时错误的被卡住。
这就是说,它是很容易做到,你想用什么新斯卡拉2.10反射API :
def anyToMap[A: scala.reflect.runtime.universe.TypeTag](a: A) = {
import scala.reflect.runtime.universe._
val mirror = runtimeMirror(a.getClass.getClassLoader)
def a2m(x: Any, t: Type): Any = {
val xm = mirror reflect x
val members = t.declarations.collect {
case acc: MethodSymbol if acc.isCaseAccessor =>
acc.name.decoded -> a2m((xm reflectMethod acc)(), acc.typeSignature)
}.toMap
if (members.isEmpty) x else members
}
a2m(a, typeOf[A])
}
然后:
scala> println(anyToMap(x))
Map(myInt -> 11, myInner -> Map(param1 -> hello, param2 -> world))
不这样做,虽然。 事实上,你应该做你的绝对最好完全避免在运行时反射斯卡拉 - 它真的几乎没有必要。 因为如果你决定,你必须使用运行时反射,你就要去使用Scala的反射API比Java的更好,我只张贴这个答案。
只是递归调用它。 所以
def getCCParams(cc: AnyRef) =
(Map[String, Any]() /: cc.getClass.getDeclaredFields) {(a, f) =>
f.setAccessible(true)
val value = f.get(cc) match {
// this covers tuples as well as case classes, so there may be a more specific way
case caseClassInstance: Product => getCCParams(caseClassInstance)
case x => x
}
a + (f.getName -> value)
}
这是一种基于无形更加原则性的解决方案。 https://github.com/yongjiaw/datacrafts
class NoSchemaTest extends FlatSpec with ShapelessProduct.Implicits {
"Marshalling and unmarshalling with Map" should "be successful" in {
val op = NoSchema.of[TestClass]
assert(
op.operator.marshal(
Map(
"v1" -> 10,
"v5" -> Map("_2" -> 12),
"v3" -> Iterable(Seq("v21" -> 3)),
"v6" -> TestClass3(v31 = 5)
)) == TestClass(
v1 = 10,
v5 = (null, 12),
v3 = Some(Seq(Some(
TestClass2(
v21 = 3,
v22 = null
)))),
v6 = Some(TestClass3(v31 = 5)),
v2 = None,
v4 = null
)
)
assert(
op.operator.unmarshal(
TestClass(
v1 = 1,
v2 = null
)
) == Map(
"v1" -> 1,
"v2" -> null,
// the rest are default values
"v6" -> null,
"v5" -> Map("_2" -> 2, "_1" -> "a"),
"v4" -> null,
"v3" -> Seq(
Map(
"v21" -> 3,
"v22" -> Map("v" -> Map(), "v32" -> Seq(12.0), "v31" -> 0)
)
)
)
)
}
}
object NoSchemaTest {
case class TestClass(v1: Int,
v2: Option[Seq[Option[Double]]] = None,
v3: Option[Seq[Option[TestClass2]]] = Some(Seq(Some(TestClass2()))),
v4: Seq[Int] = null,
v5: (String, Int) = ("a", 2),
v6: Option[TestClass3] = None
)
case class TestClass2(v21: Int = 3,
v22: TestClass3 = TestClass3(0)
)
case class TestClass3(v31: Int,
v32: Iterable[Double] = Seq(12),
v: Map[String, Int] = Map.empty
)
}
trait DefaultRule extends Operation.Rule {
override def getOperator[V](operation: Operation[V]): Operation.Operator[V] = {
operation.context.noSchema match {
case _: Primitive[V] => new PrimitiveOperator[V](operation)
case shapeless: ShapelessProduct[V, _] =>
new ShapelessProductMapper[V](operation, shapeless)
case option: OptionContainer[_] =>
new OptionOperator[option.Elem](
option.element, operation.asInstanceOf[Operation[Option[option.Elem]]])
.asInstanceOf[Operation.Operator[V]]
case map: MapContainer[_] =>
new MapOperator[map.Elem](
map.element, operation.asInstanceOf[Operation[Map[String, map.Elem]]])
.asInstanceOf[Operation.Operator[V]]
case seq: SeqContainer[_] =>
new SeqOperator[seq.Elem](
seq.element, operation.asInstanceOf[Operation[Seq[seq.Elem]]])
.asInstanceOf[Operation.Operator[V]]
case iterable: IterableContainer[_] =>
new IterableOperator[iterable.Elem](
iterable.element, operation.asInstanceOf[Operation[Iterable[iterable.Elem]]])
.asInstanceOf[Operation.Operator[V]]
}}}