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

前端 未结 4 410
梦如初夏
梦如初夏 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 09:41

    Maybe someone who does this all the time can chime in, but it took me this many steps to reproduce it.

    I start the REPL -i, so autocomplete is broken. That puts me at a disadvantage.

    scala> class X(i: Int)
    defined class X
    
    scala> typeTag[X]
    res0: reflect.runtime.universe.TypeTag[X] = TypeTag[X]
    
    scala> .tpe
    res1: reflect.runtime.universe.Type = X
    
    scala> .members
    res2: reflect.runtime.universe.MemberScope = Scopes(constructor X, value i, method $asInstanceOf, method $isInstanceOf, method synchronized, method ##, method !=, method ==, method ne, method eq, constructor Object, method notifyAll, method notify, method clone, method getClass, method hashCode, method toString, method equals, method wait, method wait, method wait, method finalize, method asInstanceOf, method isInstanceOf, method !=, method ==)
    
    scala> res2.filter(s => s.isMethod && s.asMethod.isConstructor)
    res4: Iterable[reflect.runtime.universe.Symbol] = SynchronizedOps(constructor X, constructor Object)
    
    scala> res4.iterator.next
    res7: reflect.runtime.universe.Symbol = constructor X
    
    scala> .typeSignature
    res8: reflect.runtime.universe.Type = (i: scala.Int)X
    
    scala> res7.asMethod
    res11: reflect.runtime.universe.MethodSymbol = constructor X
    
    scala> res1.typeSymbol.asClass
    res13: reflect.runtime.universe.ClassSymbol = class X
    
    scala> currentMirror reflectClass res13
    res14: reflect.runtime.universe.ClassMirror = class mirror for X (bound to null)
    
    scala> res14 reflectConstructor res11
    res16: reflect.runtime.universe.MethodMirror = constructor mirror for X.(i: scala.Int): X (bound to null)
    
    scala> res16(7)
    res17: Any = X@28730c5a
    
    scala> .asInstanceOf[X]
    res18: X = X@28730c5a
    

提交回复
热议问题