Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I do a method call after a @Grab declaration in a Groovy script?

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? ​

like image 938
Phuong LeCong Avatar asked Apr 20 '11 08:04

Phuong LeCong


People also ask

How do you call a method in Groovy script?

In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.

What is @grab in Groovy?

50.1. Standard Groovy includes a @Grab annotation which allows you to declare dependencies on a third-party libraries. This useful technique allows Groovy to download jars in the same way as Maven or Gradle would; but without requiring you to use a build tool.

How do I declare a variable in Groovy?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.


1 Answers

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.

like image 160
tim_yates Avatar answered Oct 11 '22 13:10

tim_yates