简体   繁体   中英

Do Lombok Builders use Reflection?

Do Lombok Builders use Reflection?

or does it also add the necessary code pre-compile?

The official site is pretty clear on how @Builder works:

@Builder can be placed on a class, or on a constructor, or on a method. While the "on a class" and "on a constructor" mode are the most common use-case, @Builder is most easily explained with the "method" use-case.

A method annotated with @Builder (from now on called the target ) causes the following 7 things to be generated:

  • An inner static class named FooBuilder , with the same type arguments as the static method (called the builder ).
  • In the builder : One private non-static non-final field for each parameter of the target .
  • In the builder : A package private no-args empty constructor.
  • In the builder : A 'setter'-like method for each parameter of the target : It has the same type as that parameter and the same name. It returns the builder itself, so that the setter calls can be chained, as in the above example.
  • In the builder : A build() method which calls the method, passing in each field. It returns the same type that the target returns.
  • In the builder : A sensible toString() implementation.
  • In the class containing the target : A builder() method, which creates a new instance of the builder .

So for example, it might look like this:

public static class FooBuilder {
    private String abc;
    private String def;

    FooBuilder() {}

    public FooBuilder abc(String abc) {
        this.abc = abc;
        return this;
    }

    public FooBuilder def(String def) {
        this.def = def;
        return this;
    }

    public Foo build() {
        return new Foo(abc, def);
    }

    @Override
    public String toString() {
        return "FooBuilder{abc: " + abc + ", def: " + def + "}";
    }
}

There's definitely no reflection at all as Lombok uses sort of code generation. It works on the AST (Abstract Syntax Tree) level, ie, it works with the parsed source, somewhere between the source code and the bytecode.

A part of Lombok is delombok , which shows you rather exactly what code was generated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM