Is there a way to convert Groovy to Java automatically?

luiscolorado picture luiscolorado · Mar 14, 2011 · Viewed 29.1k times · Source

I have inherited significant amounts of Groovy code, and I have found it difficult to maintain for several reasons:

  1. Very often it's hard to tell what's the type of a variable.
  2. Corollary: it's easy to modify a variable with a different type, and not being aware of it.
  3. Many errors will be discovered until run-time (which is scary if your unit testing doesn't cover pretty much everything).
  4. The type of the parameters is basically ignored.
  5. The IDE I'm using (STS Pro) is useful, but far behind from Java. For instance, refactoring is just not available.
  6. Suggestions are available some times, others, not.

Although I appreciate the compactness of the language, maintenance has been difficult and cumbersome.

I have tried to manually convert some pieces to Java, it's been a pain. Are you aware of any tools or plugins that help with this conversion?

Answer

af1n picture af1n · Mar 4, 2014

IntelliJ IDEA has a quite decent support for refactoring of groovy code. It also has a source code level converter from Groovy -> Java. Most of the time it generates code that does not compile, but it may help to get you started with the process of converting the code. Groovy code:

class HelloWorld {
def name
def greet() { "Hello ${name}" }
int add(int a, int b) {
    return a+b;
}
}

Converted Java code:

public class HelloWorld {
public GString greet() {
    return "Hello " + String.valueOf(name);
}

public int add(int a, int b) {
    return a + b;
}

public Object getName() {
    return name;
}

public void setName(Object name) {
    this.name = name;
}

private Object name;
}