Reputation: 999
I'm trying to use Groovy (which is new to me) to replace Java value object classes with a Groovy equivalent and thus obtain a cleaner and more concise code, while remaining compatible with the rest of the Java codebase. (if this attempt fails, I may fall back to Google @AutoValue
.)
The value objects shall remain instantiable from Java code using the builder pattern. The setter methods shall be without prefix and ideally the builder should be instantiable through a static method with configurable name.
@groovy.transform.builder.Builder
's Javadoc mentions it can be used "if you need Java integration" and I see it also has configuration parameters which looks promising, but I did not figure out how to use it from Java code.
Here is an attempt, where I do not know what to substitute for X:
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.class
and target/classes/com/hello/GroovyGreeting$com/hello/GroovyGreetingBuilder.class
. The '$' in there is really strange and prevents referencing it (import com.hello.GroovyGreeting$com.hello.GroovyGreetingBuilder
is illegal). Also for some reason in IntelliJ IDEA I can decompile GroovyGreetingBuilder.class
but not GroovyGreeting.class
(no reaction when trying to open it).
Upvotes: 5
Views: 948
Reputation: 31
I had exactly the same problem. After investigating the code of the Builder strategies, I managed to make it work by explicitly specifying the builderClassName.
package alfa.beta
@Builder(builderClassName = 'PageLayoutBuilder')
class PageLayout
I can see that the generated builder is alfa/beta/PageLayout$PageLayoutBuilder now.
I filed a JIRA issue GROOVY-7501 for this.
Upvotes: 3