【发布时间】:2018-08-26 11:47:07
【问题描述】:
我有一个“动态实例化案例类”的梦想——并根据每个字段类型为字段提供一些虚拟数据(我稍后会为此创建一些规则)
到目前为止,我有一些代码可以与 String 的案例类一起使用; Long 或 Int ...如果可以处理嵌入式案例类,我有点坚持
所以我可以实例化case class RequiredAPIResponse (stringValue: String, longValue: Long, intVlaue: Int)
但不是外部;外部是...
case class Inner (deep: String)
case class Outer (in : Inner)
代码是
def fill[T <: Object]()(implicit mf: ClassTag[T]) : T = {
val declaredConstructors = mf.runtimeClass.getDeclaredConstructors
if (declaredConstructors.length != 1)
Logger.error(/*T.toString + */" has " + declaredConstructors.length + " constructors --- only 1 currently supported.")
val constructor = declaredConstructors.headOption.get
val m = constructor.getParameterTypes.map(p => {
Logger.info("getName " + p.getName +" --- getCanonicalName " + p.getCanonicalName)
Logger.info(p.getCanonicalName)
p.getCanonicalName match {
case "java.lang.String" => /*"Name"->*/ val s : java.lang.String = "DEFAULT STRING"
s
case "long" => /*"Name"-> */ val l : java.lang.Long = new java.lang.Long(99)
l
case "int" => /*"Name"->*/ val i : java.lang.Integer = new java.lang.Integer(99)
i
case _ => /*"Name"->*/
So around here I am stuck!
//THIS IS MADE UP :) But I want to get the "Type" and recursively call fill
//fill[p # Type] <- not real scala code
//I can get it to work in a hard coded manner
//fill[Inner]
}
})
我觉得Scala: How to invoke method with type parameter and manifest without knowing the type at compile time? 上的最后一个答案是一个答案的起点。 所以不要使用 T <: object fill classtag typetag>
这段代码从 - How can I transform a Map to a case class in Scala? 开始 - 它提到(正如 Lift-Framework 所做的那样)我确实有 liftweb 源代码;但到目前为止,还没有成功解开它的所有秘密。
编辑 --- 根据 Imm 的观点,我可以使用以下代码(对他的回答进行了一些小的更新)
def fillInner(cls: Class[_]) : Object = {
val declaredConstructors = cls.getDeclaredConstructors
if (declaredConstructors.length != 1)
Logger.error(/*T.toString + */ " has " + declaredConstructors.length + " constructors --- only 1 currently supported.")
val constructor = declaredConstructors.headOption.get
val m = constructor.getParameterTypes.map(p => {
Logger.info("getName " + p.getName + " --- getCanonicalName " + p.getCanonicalName)
Logger.info(p.getCanonicalName)
p.getCanonicalName match {
case "java.lang.String" => /*"Name"->*/ val s: java.lang.String = "DEFAULT STRING"
s
case "long" => /*"Name"-> */ val l: java.lang.Long = new java.lang.Long(99)
l
case "int" => /*"Name"->*/ val i: java.lang.Integer = new java.lang.Integer(99)
i
case _ => fillInner(p)
}
})
constructor.newInstance(m: _*).asInstanceOf[Object]
}
def fill[T](implicit mf: ClassTag[T]) : T = fillInner(mf.runtimeClass).asInstanceOf[T]
谢谢, 布伦特
【问题讨论】:
-
可能 ScalaTest 或 ScalaCheck 有类似的东西用于自动测试用例生成。无形当然是一种选择(从答案看来 Kiama 也可能是):stackoverflow.com/questions/13402378/…
标签: scala reflection types