如何使用Scala宏获取构造函数参数名称

如何使用Scala宏获取构造函数参数名称,scala,reflection,constructor,macros,scala-macros,Scala,Reflection,Constructor,Macros,Scala Macros,有没有办法使用scala宏获取给定构造函数的参数名 谢谢这份REPL成绩单应该能让你走了,我希望: Welcome to Scala version 2.10.0-RC5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_09). Type in expressions to have them evaluated. Type :help for more information. scala> :power ** Power User mod

有没有办法使用scala宏获取给定构造函数的参数名


谢谢

这份REPL成绩单应该能让你走了,我希望:

Welcome to Scala version 2.10.0-RC5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_09).
Type in expressions to have them evaluated.
Type :help for more information.

scala> :power
** Power User mode enabled - BEEP WHIR GYVE **
** :phase has been set to 'typer'.          **
** scala.tools.nsc._ has been imported      **
** global._, definitions._ also imported    **
** Try  :help, :vals, power.<tab>           **

scala> class Foo(x: Int, y: Float)
defined class Foo

scala> (typeOf[Foo].members find (_.isConstructor)).get.tpe.params map (_.name)
res1: List[$r.intp.global.Symbol#NameType] = List(x, y)
欢迎使用Scala版本2.10.0-RC5(Java热点(TM)64位服务器虚拟机,Java 1.7.009)。
键入要计算的表达式。
键入:有关详细信息的帮助。
scala>:电源
**电源用户模式已启用-哔哔声**
**:相位已设置为“typer”**
**scala.tools.nsc.\已导入**
**全局。\定义。\也已导入**
**尝试:帮助、:VAL、电源**
scala>类Foo(x:Int,y:Float)
定义类Foo
scala>(typeOf[Foo]。成员查找(u.isConstructor)).get.tpe.params映射(u.name)
res1:List[$r.intp.global.Symbol#NameType]=List(x,y)

请注意,Paul Butcher回答中的
:power
方法允许您访问内部API,如果您试图在宏中执行此操作(或者在REPL之外的运行时反射),则可能不需要或不需要内部API

因此,例如,在公共反射API中对
成员提供的普通旧
符号
调用
isConstructor
将不起作用,您首先需要确保您有一个
MethodSymbol
。类似于
tpe
。当然,您可以在非REPL代码中强制转换到内部API,但这是危险的,也是不必要的。以下是一个更好的解决方案:

import scala.reflect.runtime.universe._

class Foo(name: String, i: Int) { def this(name: String) = this(name, 0) }

typeOf[Foo].declaration(nme.CONSTRUCTOR).asTerm.alternatives.collect {
  case m: MethodSymbol => m.paramss.map(_.map(_.name))
}
或者只是:

typeOf[Foo].declarations.collect {
  case m: MethodSymbol if m.isConstructor => m.paramss.map(_.map(_.name))
}
这两项都将为您提供以下信息:

List(List(List(name, i)), List(List(name)))

如所愿。我在这里使用了运行时反射来简化示例,但这与从宏中的
上下文获得的
宇宙
的工作方式完全相同。

啊-关于:电源模式的好观点。谢谢你救了我的脸红!如何在编译时使它在scala类中工作?