[英]Scala Reflect Case Class Apply Method Runtime
How do you reflect a case class's members at run time without an instance? 您如何在没有实例的情况下在运行时反映案例类的成员?
For example if I have the following case class: 例如,如果我有以下案例类:
package com.abc
object Holder {
case class Hello(message:String,count:Int)
}
I would of thought although I don't have an instance of Hello to reflect I could reflect the Companion Object apply method and inspect the arguments to know about what members it has? 我会考虑,尽管我没有Hello实例来反映我可以反映Companion Object apply方法并检查参数以了解它具有哪些成员?
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val module = mirror.staticModule("com.abc.Holder$Hello")
val instance = mirror.reflectModule(module).symbol.typeSignature.member(TermName("apply")).asMethod.paramLists
instance.foreach(println)
However this returns "none" is not a method. 但是,此返回“ none”不是方法。 So it doesn't have an apply method?
因此,它没有应用方法?
I came to the below conclusion. 我得出以下结论。 Is there any way to use Scala reflection instead of Class.forName?
有什么方法可以使用Scala反射代替Class.forName吗?
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val classSymbol = mirror.classSymbol(Class.forName("com.quantexa.anonymizer.FiuModel$Customer"))
val classApply = classSymbol.companion.typeSignature.member(TermName("apply")).asMethod
val members = classApply.paramLists.flatten.map(x => (x.asTerm.name,x.typeSignature))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.