Lombok 中的语法“@__()”是什么意思?

What does the syntax `@__()` mean in Lombok?

我已经与 Lombok 合作并积极使用了 2 个月。 Java 我比较熟悉。但是,我第一次遇到该语言中的以下语法结构:

@RequiredArgsController(onController = @__(@Autowired))
                                       ^^^

这是什么意思,它是如何编译的?

这是一个实验性的 Lombok 语法,创建它是为了在引用多个注释时支持一个间接层,而不是使用 Class<?>[]

The syntax is a little strange; to use any of the 3 onX features, you must wrap the annotations to be applied to the constructor / method / parameter in @__(@AnnotationGoesHere). To apply multiple annotations, use @__({@Annotation1, @Annotation2}). The annotations can themselves obviously have parameters as well.

https://projectlombok.org/features/experimental/onX.html

Lombok 开发者的解释Roel Spilker:

The reason for it is that javac already resolves annotations in the parsing phase, and gives errors if it can determine that the annotations are invalid. By using a non-existent annotation @__ it cannot determine it is bogus (it might be created by an annotation processor) and will not give an error right away. That gives Lombok the time to do its work and remove the @__ from the code.

这意味着生成的构造函数(不是控制器)也将添加 @Autowired 注释,以便 spring 可以发挥其魔力。使用 lombok,您可以像

这样编写代码
@RequiredArgsConstructor(onConstructor=@__(@Autowired(required=true)))
public class FooController {
    private final FooService service;
    interface FooService {}
}

lombok 会将其 during compilation 转换为

public class FooController {
    private final FooService service;
    @Autowired(required=true)
    public FooController(FooService service) {
        this.service = service;
    }
}

@__用来克服注解的类型限制因为

@interface MultipleAnnotations {
    Annotation[] value();
}

不起作用,因为所有注释的超类型本身不是注释并且

@interface MultipleAnnotations {
    Class<? extends Annotation>[] value();
}

不允许在注释中使用参数:@MultipleAnnotations(SomeAnnotation.class)

对于对这种奇怪的语法感到困惑的 JDK8 用户,有一种更简洁的方法,如前所述 here - On javac8 and up, you add an underscore after onMethod, onParam, or onConstructor.

所以它会从@RequiredArgsController(onController = @__(@Autowired))变为@RequiredArgsController(onController_ = @Autowired)