首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Scala 2.10:动态实例化案例类

Scala 2.10:动态实例化案例类
EN

Stack Overflow用户
提问于 2015-01-07 16:01:42
回答 2查看 2.5K关注 0票数 3

我梦想“动态实例化案例类”--并根据每个字段类型为字段提供一些虚拟数据(稍后我将为此创建一些规则)。

到目前为止,我有一些与StringLongInt .如果有可能处理嵌入式案例类的话,我会有点拘泥于此。

所以我可以实例化case class RequiredAPIResponse (stringValue: String, longValue: Long, intVlaue: Int)

但不是外星,外星在.

代码语言:javascript
复制
case class Inner (deep: String)
case class Outer (in : Inner)

代码是

代码语言:javascript
复制
 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的要点,我有下面的代码可以工作(对他的回答做一些小的更新)

代码语言:javascript
复制
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]

谢谢,布伦特

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-01-07 16:40:05

实际上,您并不是在使用ClassTag,而是Class[_],而且没有一个是typesafe (它只是Java反射),所以只需递归地传递Class[_]

代码语言:javascript
复制
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]

但是,您可能可以以一种类型错误的方式完成您想要做的事情,也许可以使用无形状的:

代码语言:javascript
复制
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] (最终只包含有Suppliers的值)获得一个HList;您只需要更多的形状(在版本1或2中是不同的,而且已经有一段时间没有这样做了,所以我不记得具体情况)来在这些类和case类之间来回转换。

票数 2
EN

Stack Overflow用户

发布于 2018-08-25 23:06:33

如果您只在测试中使用它,最好的方法是使用Scala/Java反射。

与使用宏相比,它的优点是编译速度更快。与使用标量相关库相比,API具有更好的优点。

设置它有点牵扯到。下面是一个完整的工作代码,您可以将其复制到代码库中:

代码语言:javascript
复制
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")
  }
}

当你想使用它的时候,你可以打电话给:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27823448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档