How to pass variable to groovy code in Intellij ID

2019-04-07 17:20发布

I have a groovyScript in my Intellij IDEA live template, like this :

groovyScript("D:/test.groovy","", v1)

on my D:/test.groovy i have a code like this:

if ( v1 == 'abc') {
    'abc'
}

Now I want to pass v1 variable into test.groovy ,can any one help me how can I do this?

3条回答
▲ chillily
2楼-- · 2019-04-07 17:52

I found a solution.

I was needing to calculate a CRC32 of the qualified class name using live models

I used it like this:

groovyScript("   
def crc = new java.util.zip.CRC32().with { update _1.bytes; value }; 
return Long.toHexString(crc);  
", qualifiedClassName())

enter image description here

then the result is

enter image description here

查看更多
Melony?
3楼-- · 2019-04-07 18:04

The arguments to groovyScript macro are bound to script variables named _1, _2 etc. This is also described at groovyScript help at Edit Template Variables Dialog / Live Template Variables.

查看更多
Viruses.
4楼-- · 2019-04-07 18:18

For exemplification purposes I made a live template which is printing a comment with the current class and current method.

This is how my live template is defined:

enter image description here

And here is how I edited the variableResolvedWithGroovyScript variable:

enter image description here

The Expression for the given variable has the follwing value:

groovyScript("return \"// Current Class:\" + _1 + \". Current Method:\"+ _2 ", className(),methodName())

As you can see, in this case the _1(which acts like a variable in the groovy script) takes the value of the first parameter which is the class name, and the _2 takes the value of the second parameter which is the method name. If another parameter is needed the _3 will be used in the groovy script to reference the given parameter.

查看更多
登录 后发表回答