簡體   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