[英]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? 如果SomeClass
是在Java中定义的,那么主构造函数的概念不存在?
Yep, there's a method on MethodSymbolApi
called isPrimaryConstructor
that does precisely this: 是的,在MethodSymbolApi
上有一个名为isPrimaryConstructor
的方法,它正是这样做的:
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. 对于Java类,您只需获取源文件中定义的第一个构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.