0

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?

1 Answer 1

1
classOf[A].getConstructors()(1).newInstance(1)

you can simply use the Java reflection to newInstance to initiate with multiple constructor.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.