You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy如何通过拼接生成的变量名解析对应变量值?

解决Groovy通过拼接变量名获取变量值的问题

你当前的代码只是拼接出了变量名字符串sMonth,并没有读取这个变量对应的实际值。在Groovy里可以通过以下方式实现需求:

方法一:利用binding对象(脚本级变量适用)

Groovy脚本里的顶级变量会被存储到binding对象中,你可以通过它的getVariable方法,根据变量名字符串获取对应的值:

def sMonth = 'Jan'
def aVar = 'Month'
def bVar = 's' + aVar
println(binding.getVariable(bVar)) // 输出 Jan

方法二:元编程方式(类内成员变量适用)

如果你的代码是在类内部而非顶级脚本,可通过元类的getProperty方法实现:

class Test {
    def sMonth = 'Jan'
    
    static void main(String[] args) {
        def obj = new Test()
        def aVar = 'Month'
        def bVar = 's' + aVar
        println(obj.metaClass.getProperty(obj, bVar)) // 输出 Jan
    }
}

内容的提问来源于stack exchange,提问作者Richard Schaefer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 01:35:53