How to create an instance of type T at runtime with TypeTags

前端 未结 4 406
梦如初夏
梦如初夏 2020-12-24 09:14

Here below is how to create a new instance of type T at runtime with Manifest:

trait MyTrait
class MyClass1(val name: String) extends MyTrait
cl         


        
4条回答
  •  春和景丽
    2020-12-24 10:01

    object BeanFactory {
    
      import scala.reflect.runtime.universe._
      import scala.reflect.runtime.{universe => ru}
    
      def createBean[T: TypeTag](): Option[T] = {
        val typee = ru.typeOf[T]
        val constructor = typee.decl(ru.termNames.CONSTRUCTOR).asMethod
        if (constructor.isPrivate) {
          println("private class can not created ")
          None
        } else {
          val classMirror = ru.runtimeMirror(getClass.getClassLoader).reflectClass(typee.typeSymbol.asClass)
          val constructorMethod = classMirror.reflectConstructor(constructor)
          val params = constructor.paramLists.flatten.map(par => {
            if (par.typeSignature =:= typeOf[Int]) {
              0
            } else {
              if (par.typeSignature =:= typeOf[String]) {
                ""
              } else {
                if (par.typeSignature =:= typeOf[Double]) {
                  0.0
                } else {
                  if (par.typeSignature =:= typeOf[Float]) {
                    0.0f
                  } else {
                    if (par.typeSignature =:= typeOf[Char]) {
                      ""
                    } else {
                      if (par.typeSignature =:= typeOf[Boolean]) {
                        false
                      } else {
                        null
                      }
                    }
                  }
                }
              }
            }
    
          })
          Some(constructorMethod(params: _*).asInstanceOf[T])
        }
      }
    }
    

    This may end up with your problem

提交回复
热议问题