简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM