Call Groovy builder from Java

I'm trying to use Groovy (which is new to me) to replace the Java value object classes with the Groovy equivalent and thus get cleaner and more concise code, while remaining compatible with the rest of the Java codebook. (If this attempt failed, I can return to Google @AutoValue.)

Value objects must remain instances of Java code using the builder pattern. The setter methods should be without a prefix, and ideally, the builder should be realistic using a static method with a custom name.

@groovy.transform.builder.Builder Javadoc mentions that it can be used “if you need integration with Java,” and I see that it also has configuration options that look promising, but I did not understand how to use it from Java code.

Here is an attempt when I don't know what to replace X with:

Greeting.groovy:

import groovy.transform.Immutable
import groovy.transform.builder.Builder

@Immutable
@Builder
public class GroovyGreeting {
  String message
}

GroovyGreetingTest.java:

GroovyGreeting g = X.message("foo").build();

EDIT: 2 classes are generated, target/classes/com/hello/GroovyGreeting.classand target/classes/com/hello/GroovyGreeting$com/hello/GroovyGreetingBuilder.class. "$" There is really strange and does not allow you to refer to it ( import com.hello.GroovyGreeting$com.hello.GroovyGreetingBuilderis illegal). Also for some reason in IntelliJ IDEA I can decompile GroovyGreetingBuilder.class, but not GroovyGreeting.class(when I try to open it, I don’t respond).

+4
source share
1 answer

I had exactly the same problem. After examining the Builder strategy code, I managed to get it to work by explicitly specifying the name builderClassName.

package alfa.beta

@Builder(builderClassName = 'PageLayoutBuilder')
class PageLayout

I see that the generated builder is now alfa / beta / PageLayout $ PageLayoutBuilder.

JIRA- GROOVY -7501 .

+3

All Articles