你可以得到这样一个类的所有构造函数:
import scala.reflect.runtime.universe._
val ctor = typeOf[SomeClass].declaration(nme.CONSTRUCTOR).asTerm.alternatives
Run Code Online (Sandbox Code Playgroud)
有没有办法知道哪一个是主要的构造函数?它总是列表中的第一个吗?SomeClass在Java中定义的主要构造函数的概念不存在的情况下会发生什么?
是的,有一个MethodSymbolApi被调用的方法isPrimaryConstructor正是这样做的:
val primary: Option[MethodSymbol] = typeOf[SomeClass].declaration(
nme.CONSTRUCTOR
).asTerm.alternatives.collectFirst {
case ctor: MethodSymbol if ctor.isPrimaryConstructor => ctor
}
Run Code Online (Sandbox Code Playgroud)
对于Java类,您只需获取源文件中定义的第一个构造函数.