[英]How to create new instance of Scala class with context bound via Java reflection using only zero argument constructor?
[英]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.