You can get all the constructors of a class like this:
import scala.reflect.runtime.universe._
val ctor = typeOf[SomeClass].declaration(nme.CONSTRUCTOR).asTerm.alternatives
Is there a way to know which one is the primary constructor? Is it always the first in the list?
What happens in case SomeClass
is defined in Java where the concept of primary constructor doesn't exist?
Yep, there's a method on MethodSymbolApi
called isPrimaryConstructor
that does precisely this:
val primary: Option[MethodSymbol] = typeOf[SomeClass].declaration(
nme.CONSTRUCTOR
).asTerm.alternatives.collectFirst {
case ctor: MethodSymbol if ctor.isPrimaryConstructor => ctor
}
In the case of a Java class, you'll just get the first constructor defined in the source file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With