Lombok: @Builder on non-static inner classes does not work.

Created on 16 Feb 2017  路  6Comments  路  Source: projectlombok/lombok

Tests case coming up for more detail on this.

Probably correct solution:

Generate the builder method and the builderclass as a sibling to the inner; there does not appear to be anything else that's workable.

For now you just get an error that 'static' is not allowed here; that'll do fine until we get around to solving this properly.

accepted low-priority

All 6 comments

Can you please prioritize this?
meanwhile my hackfix

public class SearchClient {

  private final Service service;

  @Autowired
  public SearchClient(Service service) {
    this.service = service;
  }

  @AllArgsConstructor(access = AccessLevel.PRIVATE)
  public class Requester {

    private final String source;

    public void sendRequest() {
      service.send(source);
    }
  }
  //hackfix for https://github.com/rzwitserloot/lombok/issues/1302
  @Builder
  private Requester createRequester(String source) {
    return new Requester(source);
  }

}

For now you just get an error that 'static' is not allowed here; that'll do fine until we get around to solving this properly.

@rzwitserloot what exactly are you suggesting here? I cannot compile an inner class with a builder annotation unless that inner class is static. Compilation fails with java: modifier static not allowed here. Making any inner classes static has been my workaround for a while but now I'm trying to use these classes in a context where the static classes are causing an issue (FreeMarker templates). Any tips?

Thanks @rspilker for the jargon clarification. Using the correct terminology, do you have any advice for getting @Builder annotations working on inner classes? I'm only able to add them to outer classes and static nested classes.

Probably correct solution:

Generate the builder method and the builderclass as a sibling to the inner

Hi @rzwitserloot ,

IMO, this might be little trickier than that. The _Builder_ class being static inner class of the top most class(i.e being a sibling for the inner class), makes it's not able to instantiate "the inner class" within the build() method of it. (The compiler might throw "_..cannot be referenced from a static context_" like error). The only way the build() method the static inner builder of the inner class is, passing the reference of top most class to it(or new'ing it using the constructor). Even conceptually, building a inner class's object without wrapping class's object us just wrong.

Apart from that I have another concern regarding the inner classes builder static class being public.

Hope this helps, I just tried to fix this bug and only after realized that this would be more complex than I thought. cheers..!

Was this page helpful?
0 / 5 - 0 ratings