![](/img/trans.png)
[英]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.