为什么我不能在Groovy脚本中的@Grab声明之后进行方法调用? [英] Why can't I do a method call after a @Grab declaration in a Groovy script?

查看:567
本文介绍了为什么我不能在Groovy脚本中的@Grab声明之后进行方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建DSL并使用Global AST Transform来完成此操作。该脚本正在编译 groovyc 很好,但我希望能够让用户使用Grab / Grape来拉动JAR并让它正确执行作为一个时髦的脚本。然后,我发现我无法正确地做到这一点,因为如果在@Grab调用后没有方法声明或导入语句,脚本中会出现分析错误。

下面是一个例子:

  @Grab(group =' mysql',module ='mysql-connector-java',version ='5.1.6')

printlnHello World!

它看起来应该可以工作,但它会抱怨(这里是输出 GroovyConsole Script ):

  startup failed:
Script1.groovy:4:unexpected token:println @ line 4,column 1.
printlnhello
^

1错误

尝试不同的操作可以使它像导入语句一样工作:

  @Grab(group ='mysql',module ='mysql-connector-java',version ='5.1.6')
import groovy.lang.Object
printlnHello World!

或者一种方法的推断:

 @Grab(group ='mysql',module ='mysql-connector-java',version ='5.1.6')
def hello(){}
printlnHello World!

这是解析器中的错误吗?

解决方案

Grab只能用作特定目标的注解

  @Target(value = {CONSTRUCTOR,FIELD,LOCAL_VARIABLE,METHOD,PARAMETER,TYPE})

需要注解其中的一个(就像你看到的那样)。

不幸的是,Java(以及Groovy)中的注释只是出现在代码中间。

I'm trying to build a DSL and using a Global AST Transform to do it. The script is compiling with groovyc fine, but I'd like to be able to be able to have a user use Grab/Grape to pull the JAR and just have it execute right away as a groovy script.

I then found that I couldn't do it correctly because there's a parsing error in the script if there isn't a method declaration or import statement after the @Grab call.

Here's an example:

@Grab(group='mysql', module='mysql-connector-java', version='5.1.6')

println "Hello World!"

It looks like it should work, but it complains (here's the output the GroovyConsole Script):

startup failed:
Script1.groovy: 4: unexpected token: println @ line 4, column 1.
   println "hello"
   ^

1 error

Trying different things makes it work, like an import statement:

@Grab(group='mysql', module='mysql-connector-java', version='5.1.6')
import groovy.lang.Object
println "Hello World!" ​

Or a method declation:

@Grab(group='mysql', module='mysql-connector-java', version='5.1.6')
def hello() {}
println "Hello World!"

Is this a bug in the parser? ​

解决方案

Grab can only be applied as an annotation to certain targets

@Target(value={CONSTRUCTOR,FIELD,LOCAL_VARIABLE,METHOD,PARAMETER,TYPE})

So you need to annotate one of those things (like you are seeing)

There is unfortunately no way in Java (and hence Groovy) of annotations just appearing in the middle of code.

这篇关于为什么我不能在Groovy脚本中的@Grab声明之后进行方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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