[英]Scala Reflection: How to find a no-arg constructor via reflection (if there are multiple constructors) ? What is the type signature of “no-arg”?
我想以反射方式創建給定對象的副本(此對象稱為root
)。
為此,我需要創建root
類的實例。
我嘗試了http://docs.scala-lang.org/overviews/reflection/overview.html上給出的建議,但不適用於具有多個構造函數的對象。
如何找到no-arg構造函數?
我的猜測是我應該使用asTerm.alternatives.filter(_.typeSignature== ???))
來找到no-arg構造函數,但是我不確定這是正確的方法嗎?
即使這是要走的路,我也不知道應該用什么代替???
如果我正在尋找一個無參數的構造函數?
換句話說,無參數構造函數的類型簽名是什么?
在下面的代碼中, root
是我要查找其無參構造函數的對象。
編碼:
val m= runtimeMirror(getClass.getClassLoader)
val rootsMirror: InstanceMirror =m.reflect(root)
val theType: Type =m.reflect(root).symbol.toType
val classSymbol : ClassSymbol =m.reflect(root).symbol
val classMirror:ClassMirror=m.reflectClass(classSymbol)
val constructorMirror: MethodMirror = classMirror.reflectConstructor(
theType.declaration(nme.CONSTRUCTOR).asTerm.alternatives.filter(_.typeSignature== ???))
就像是:
scala> class X(i: Int) { def this() = this(1) }
defined class X
scala> typeOf[X].declarations.filter { s => s.isMethod && {
| val m = s.asMethod
| m.isConstructor && m.paramss.flatten.isEmpty }}
res2: Iterable[reflect.runtime.universe.Symbol] = SynchronizedOps(constructor X)
與以下類型略有不同:
scala> res5 filter (_ match { case MethodType(ps, t) if ps.isEmpty => true case _ => false })
res7: Iterable[reflect.runtime.universe.Type] = List(()X)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.