Unknown type: METHOD_DEF when running a groovy script – Education Career Blog

The following groovy script doesn’t compile

import java.util.concurrent.Callable

println "b";
Callable<String> callable = new Callable<String>()
      {
        String call() {
          println("C");
          return null;
        }
      };

This is the error:

org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed: C:\tmp\a.groovy: 6:
Unknown type: METHOD_DEF at line: 6
column: 9. File: C:\tmp\a.groovy @
line 6, c olumn 9.
String call() {
^

1 error

What is the cause and how to resolve?

,

Try reformatting it like this:

import java.util.concurrent.Callable

println "b";
Callable<String> callable = new Callable<String>() \
    { 
        String call() {
            println("C");
            return null;
        }
    };

Because semicolons are optional, groovy is sensitive to newlines and occasionally parses a statement in a way that is unexpected. In this case, it considers Callable<String> callable = new Callable<String>() to be an entire statement. Java is smart enough to see that it’s an anonymous inner class since the statement isn’t terminated at the end of the line, but the first line is syntatically correct groovy and stops parsing.

The solution is to escape the newline with a backslash, to force groovy to continue parsing the statement. Alternatively, you could put the opening brace at the end of the line (i.e. standard java coding style).

Leave a Comment