How to pass variable to groovy code in Intellij IDEA live templates groovy script?

三世轮回 提交于 2019-12-04 05:56:52

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:

And here is how I edited the variableResolvedWithGroovyScript variable:

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.

Peter Gromov

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.

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())

then the result is

Based on the documentation, your variables are available as _1, _2, etc. Please note that variables are passed without dollar signs (so only v1 instead of $v1$)

So your test script should look like

if ( _2 == 'abc') {
    'abc'
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!