我梦想“动态实例化案例类” - 并根据每个字段类型为字段提供一些虚拟数据(我稍后会为此创建一些规则)
到目前为止,我有一些代码适用于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&lt ;: Object;填写应该采用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]
谢谢, 布伦特
答案 0 :(得分:2)
你实际上并没有使用ClassTag
,只有Class[_]
,而且这些都不是类型安全的(它只是Java反射),所以只需传递{{1递归地:
Class[_]
但是你可以用类型安全的方式完成你想做的事情,也许可以使用Shapeless:
def fillInner(cls: Class[_]) : Any = {
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)
}
})
def fill[T: ClassTag]: T = fillInner(classOf[T].runtimeClass).asInstanceOf[T]
然后通过隐式解决方案的魔力,您可以获得trait Supplier[T] {
def supply: T
}
object Supplier[T] {
implicit val intSupplier = new Supplier[Int] {
def supply = 99
}
implicit val stringSupplier = ...
implicit val emptyHListSupplier = new Supplier[HNil] {
def supply = HNil
}
implicit def consHListSupplier[H, T <: HList](
implicit headSupplier: Supplier[H],
tailSupplier: Supplier[T]) = new Supplier[H :: T] {
def supply = headSupplier.supply :: tailSupplier.supply
}
}
个Supplier[(String :: HNil) :: Int :: HNil]
左右的HList
HList
个Supplier
最终只包含您已获得的值{{1}} S;你只需要一点点无形(在版本1或2中有所不同,而且我已经做了一段时间了,所以我不记得具体内容)来回转换那些和案例类。
答案 1 :(得分:0)
如果仅在测试中使用它,最好的方法是使用Scala / Java反射。
使用宏的优点是编译速度更快。与使用scalacheck相关的库相比,优点是API更好。
进行一些设置。这是完整的工作代码,您可以将其复制到代码库中:
import scala.reflect.api
import scala.reflect.api.{TypeCreator, Universe}
import scala.reflect.runtime.universe._
object Maker {
val mirror = runtimeMirror(getClass.getClassLoader)
var makerRunNumber = 1
def apply[T: TypeTag]: T = {
val method = typeOf[T].companion.decl(TermName("apply")).asMethod
val params = method.paramLists.head
val args = params.map { param =>
makerRunNumber += 1
param.info match {
case t if t <:< typeOf[Enumeration#Value] => chooseEnumValue(convert(t).asInstanceOf[TypeTag[_ <: Enumeration]])
case t if t =:= typeOf[Int] => makerRunNumber
case t if t =:= typeOf[Long] => makerRunNumber
case t if t =:= typeOf[Date] => new Date(Time.now.inMillis)
case t if t <:< typeOf[Option[_]] => None
case t if t =:= typeOf[String] && param.name.decodedName.toString.toLowerCase.contains("email") => s"random-$arbitrary@give.asia"
case t if t =:= typeOf[String] => s"arbitrary-$makerRunNumber"
case t if t =:= typeOf[Boolean] => false
case t if t <:< typeOf[Seq[_]] => List.empty
case t if t <:< typeOf[Map[_, _]] => Map.empty
// Add more special cases here.
case t if isCaseClass(t) => apply(convert(t))
case t => throw new Exception(s"Maker doesn't support generating $t")
}
}
val obj = mirror.reflectModule(typeOf[T].typeSymbol.companion.asModule).instance
mirror.reflect(obj).reflectMethod(method)(args:_*).asInstanceOf[T]
}
def chooseEnumValue[E <: Enumeration: TypeTag]: E#Value = {
val parentType = typeOf[E].asInstanceOf[TypeRef].pre
val valuesMethod = parentType.baseType(typeOf[Enumeration].typeSymbol).decl(TermName("values")).asMethod
val obj = mirror.reflectModule(parentType.termSymbol.asModule).instance
mirror.reflect(obj).reflectMethod(valuesMethod)().asInstanceOf[E#ValueSet].head
}
def convert(tpe: Type): TypeTag[_] = {
TypeTag.apply(
runtimeMirror(getClass.getClassLoader),
new TypeCreator {
override def apply[U <: Universe with Singleton](m: api.Mirror[U]) = {
tpe.asInstanceOf[U # Type]
}
}
)
}
def isCaseClass(t: Type) = {
t.companion.decls.exists(_.name.decodedName.toString == "apply") &&
t.decls.exists(_.name.decodedName.toString == "copy")
}
}
而且,当您要使用它时,可以致电:
val user = Maker[User]
val user2 = Maker[User].copy(email = "someemail@email.com")
上面的代码生成任意和唯一的值。它们不是完全随机的。该API非常好。考虑到它使用反射,最好在测试中使用。
在此处阅读我们的完整博客文章:https://give.engineering/2018/08/24/instantiate-case-class-with-arbitrary-value.html