#2477·lombok

[FEATURE] "simple" @PostBuild annotation

Author: MichelMunozCreated May 26, 2020Updated Sep 1, 2026

Description The idea is to have a basic, simple, ability to validate (or post-process) an object created by a builder without polluting lombok @Builder with non-building problems ; to do so :

  • have the possibility to annotate one instance no-arg-and-no-checked-throw method (of the class decorated with a builder) with a @PostBuild Example:
@Builder
public MyClass {
    private String someField;
    
    @PostBuild
    private void validation() {
        // do stuff here
    }
}
  • in the lomboked version, that method would be called by the .build() after creating the object, but before returning it (instead of creation-return currently done)

Precisions/Rationale/Benefits

  • separation of concerns: this avoids polluting @Builder with validation or other problems - the logic here is strictly build-related - "callback after object is built" (no need to support @Validators or @WhateverChecker by the builder, the validation logic is totally on developper-side in the annotated method ; and the method could be used for other things - eg. filling missing values, etc.)
  • more expressiveness: the approah presented allow for more elaborate validation because at the time of callback, all fields are already set (eg. check of coherency between multiple interdependent fields)
  • the restriction to only one instance no-arg-and-no-checked-throw seems reasonable
    • the method to call back should not have arguments
    • the method to call back should not have checked exceptions (otherwise this would pollute the signature of the .build() method)
    • one callback post build is enough, no need for more than one
    • only instance method will have access to the value of instance fields
  • maintenability of post-processing code:
    • if an unchecked exception is raised from the @PostBuild annotated method, the stack would be "clean" (readable, leads directly to existing - as opposed to generated - code)
    • validation (the annotated method) is easy to debug (it's a normal method in normal code)
  • minimal impact : the approach is totally compatible with current functioning of @Builder (eg. works if the constructor is generated by lombok or provided by the developper, etc.)

Background

Stupid-proofing To detect invalid usage at compile-time :

  • if a @PostBuild annotated method is not valid (not instance/no-arg/no throw...) : there is a compilation error
  • if more than one method is @PostBuild annotated in a @Builderdecorated class : compilation error
  • if @PostBuild is used on a non-@Builderdecorated class: compilation error