在groovy中动态执行代码 [英] executing code dynamically in groovy

查看:400
本文介绍了在groovy中动态执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在groovy中动态地运行代码。我有 someNode [0] ,它是变量 var1 中的值。

然后我给它加了双引号,就像这样

  var2 =\+ var1 +\\ \\

然后我试着运行这个



pre $
$ b $ p >我在这里看到这种类型的东西可以在属性和方法上完成。但上面的代码不起作用。给我错误

 发生错误[无法在空对象上设置属性''someNode [0]'],请参阅错误日志详情

任何帮助表示赞赏。



编辑
这是我的请求的一小部分

app:{
bundle:531323947,
cat:[
IAB1,
IAB9,
IAB9-30,
娱乐,
游戏

id:agltb3B1Yi1pbmNyDAsSA0FwcBitsL4UDA,


我试图操作的字段是 cat [0] ,它是 IAB1 (我刚刚使用了 abc someNode [0] 在我上面写的代码中,但实际上它们是 app cat [0]



另外,我使用 jsonslurper 运行上面的代码解析请求



感谢您的帮助

解决方案

执行此操作的一种方法是使用 Eval

  def request = [
app:[
bundle:531323947,
cat:[
IAB1,
IAB9,
IAB9-30,
娱乐 ,
游戏

]
]

assert request.app.cat [0] =='IAB1'
def var ='request.app.cat [0]'
Eval.me('request',request,$ var ='new value')
assert request.app.cat [0] =='新值'


I am trying to run code dynamically in groovy. I have someNode[0], which is the value, in variable var1

I then added double quotes to it like this

var2 = "\""+var1+"\""

then I tried to run this

request.abc."$var2"=Value

I saw here that something of this sort can be done on properties and methods. But the above code is not working. Giving me error

An error occurred [Cannot set property '"someNode[0]"' on null object], see error log for details

Any help is appreciated. Thanks.

Edit Heres a snippet of my request

{
   "app":{
      "bundle":"531323947",
      "cat":[
         "IAB1",
         "IAB9",
         "IAB9-30",
         "entertainment",
         "games"
      ],
      "id":"agltb3B1Yi1pbmNyDAsSA0FwcBitsL4UDA",
      .
      .

The field I am trying to manipulate is cat[0], which is IAB1 (I just used abc and someNode[0] in the code that i wrote above but actually they are app and cat[0])

Also, I parsed the request with jsonslurper befor running the above code

Thank you for your help

解决方案

One way to do this, is by Eval

def request =[
"app":[
    "bundle":"531323947",
    "cat":[
            "IAB1",
            "IAB9",
            "IAB9-30",
            "entertainment",
            "games"
    ],
]
]

assert request.app.cat[0]=='IAB1'
def var = 'request.app.cat[0]'
Eval.me('request', request, "$var = 'new value'")
assert request.app.cat[0]=='new value'

这篇关于在groovy中动态执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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