在运行时获取 Scala 变量名 [英] Get Scala variable name at runtime

查看:95
本文介绍了在运行时获取 Scala 变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在运行时获取 scala 变量的名称?

Is it possible to get the name of a scala variable at runtime?

例如是否可以编写一个函数 getIntVarName(variable: Int): String 表现如下?

E.g. is it possible to write a function getIntVarName(variable: Int): String behaving as follows?

val myInt = 3
assert("myInt" === getIntVarName(myInt))

推荐答案

基本上是做不到的.

JVM 不提供任何方法句柄(请记住,Scala 属性在字节码中编码为方法以支持统一访问原则).您能得到的最接近的方法是使用反射来查找在特定类上定义的方法列表 - 我认为这对您的特定需求没有帮助.

The JVM offers nothing by way of a Method handle (remember, Scala properties are encoded as methods in bytecode to support the uniform access principle). The closest you can get is to use reflection to find a list of methods defined on a particular class - which I appreciate doesn't help with your particular need.

可以将其作为 Scala 功能来实现,但是它需要一个编译器插件来从 AST 中获取相关的符号名称并将其作为字符串文字推送到代码中,所以不是什么我可以用一个简短的代码片段来演示:)

It is possible to implement this as a Scala feature, but it would require a compiler plugin to grab the relevant symbol name from the AST and push it into code as a string literal, so not something I could demonstrate in a short code snippet :)

反射中经常出现的另一个命名问题是方法参数.那个至少我可以帮忙.我有一个 工作中的反射库,它基于编译器生成的 scala 签名作为scalap 使用.它远未准备好投入使用,但正在积极开发中.

The other naming problem that often comes up in reflection is method parameters. That one at least I can help with. I have a work-in-progress reflection library here that's based on the compiler-generated scala signature as used by scalap. It's nowhere near being ready for serious use, but it is under active development.

这篇关于在运行时获取 Scala 变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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