繁体   English   中英

使用新的反射API,如何找到类的主要构造函数?

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

你可以得到这样一个类的所有构造函数:

import scala.reflect.runtime.universe._

val ctor = typeOf[SomeClass].declaration(nme.CONSTRUCTOR).asTerm.alternatives

有没有办法知道哪一个是主要的构造函数? 它总是列表中的第一个吗? 如果SomeClass是在Java中定义的,那么主构造函数的概念不存在?

是的,在MethodSymbolApi上有一个名为isPrimaryConstructor的方法,它正是这样做的:

val primary: Option[MethodSymbol] = typeOf[SomeClass].declaration(
  nme.CONSTRUCTOR
).asTerm.alternatives.collectFirst {
  case ctor: MethodSymbol if ctor.isPrimaryConstructor => ctor
}

对于Java类,您只需获取源文件中定义的第一个构造函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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