使用新的反射API,如何找到类的主构造函数? [英] Using the new reflection API, how to find the primary constructor of a class?

查看:41
本文介绍了使用新的反射API,如何找到类的主构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以像这样获得一个类的所有构造函数:

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

有没有办法知道哪个是主构造函数?它总是在列表中的第一个吗?如果 SomeClass 在 Java 中定义而 主构造函数 的概念不存在,会发生什么?

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?

推荐答案

是的,MethodSymbolApi 称为 isPrimaryConstructor 正是这样做的:

Yep, there's a method on MethodSymbolApi called isPrimaryConstructor that does precisely this:

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

对于 Java 类,您将获得源文件中定义的第一个构造函数.

In the case of a Java class, you'll just get the first constructor defined in the source file.

这篇关于使用新的反射API,如何找到类的主构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆