Lombok Builders 使用反射吗?

Do Lombok Builders use Reflection?

Lombok Builders 使用反射吗?

或者它是否也添加了必要的代码预编译?

The official site 非常清楚 @Builder 的工作原理:

@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.

例如,它可能看起来像这样:

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 + "}";
    }
}

绝对没有反射,因为 Lombok 使用某种 代码生成。它在 AST(抽象语法树)级别上工作,即,它在源代码和字节码之间的某个位置与解析后的源代码一起工作。

Lombok 的一部分是 delombok,它向您展示了生成的代码。