Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 467
Tobias Brandt Avatar asked May 11 '13 11:05

Tobias Brandt


1 Answers

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.

like image 167
Travis Brown Avatar answered Oct 04 '22 15:10

Travis Brown