Tobias Brandt
Tobias Brandt

Reputation: 3413

Using the new reflection API, how to find the primary constructor of a class?

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?

Upvotes: 5

Views: 752

Answers (1)

Travis Brown
Travis Brown

Reputation: 139048

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.

Upvotes: 9

Related Questions