jeudi 15 juin 2017

create an instance from type with multiple constructor in scala

I have a class I created with 2 constructors.

I want to create an instance of this class using only default constructor.

class A (arg1:Int,Arg2:String){
   def this(arg1:Int){
      this(arg1,"hello")
   }
}

here is what I tries to do:

val tpe = ru.typeOf[A]
val mirror = ru.runtimeMirror(getClass.getClassLoader)
val clsSym = tpe.typeSymbol.asClass
val clsMirror = mirror.reflectClass(clsSym)
val ctorSym = tpe.decl(ru.termNames.CONSTRUCTOR).asMethod
val method = clsMirror.reflectConstructor(ctorSym)
val newInstance = method(args:_*)

I'm getting the following error:

constructor ExampleWithCamelCase encapsulates multiple overloaded
alternatives and cannot be treated as a method. Consider invoking 
<offending symbol>.asTerm.alternatives` and manually picking the required method

is there away to choose the default constructor?





Aucun commentaire:

Enregistrer un commentaire