简体   繁体   English

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

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

You can get all the constructors of a class like this: 你可以得到这样一个类的所有构造函数:

import scala.reflect.runtime.universe._

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

Is there a way to know which one is the primary constructor? 有没有办法知道哪一个是主要的构造函数? Is it always the first in the list? 它总是列表中的第一个吗? What happens in case SomeClass is defined in Java where the concept of primary constructor doesn't exist? 如果SomeClass是在Java中定义的,那么主构造函数的概念不存在?

Yep, there's a method on MethodSymbolApi called isPrimaryConstructor that does precisely this: 是的,在MethodSymbolApi上有一个名为isPrimaryConstructor的方法,它正是这样做的:

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

In the case of a Java class, you'll just get the first constructor defined in the source file. 对于Java类,您只需获取源文件中定义的第一个构造函数。

暂无
暂无

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

相关问题 如何使用零参数构造函数创建具有通过Java反射绑定的上下文的Scala类的新实例? - How to create new instance of Scala class with context bound via Java reflection using only zero argument constructor? 如何使用反射获取默认构造函数参数? - How to get default constructor parameter using reflection? 如何从MemberScope反射中找到超类 - How to find super class from MemberScope reflection Scala反射:如何通过反射找到无参数构造函数(如果有多个构造函数)? “ no-arg”的类型签名是什么? - Scala Reflection: How to find a no-arg constructor via reflection (if there are multiple constructors) ? What is the type signature of “no-arg”? 在Scala中,如何在类的主构造函数中定义局部参数? - In Scala, how do you define a local parameter in the primary constructor of a class? 在 Scala 反射中使用参数构造函数创建类 - Creating class with parameter constructor in Scala reflection 如何执行反射以找到在Scala中扩展基类的所有类? - How perform reflection to find all classes that extend a base class in Scala? 如果我们在构造函数中定义了默认值,如何使用 Scala 反射调用默认构造函数 - How to invoke default constructor using scala reflection if we have default value defined in our constructor 如何将计算的对象从主类构造函数传递给超类型构造函数? - How should I pass a computed object from the primary class constructor to the supertype constructor? 使用Scala反射获取构造函数参数值 - Get constructor parameter values using scala reflection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM