Lombok - 在构造函数输入参数中保留字段的注释

Lombok - retain field's annotation in constructor input params

Lombok 在自动生成构造函数时遗漏了字段的注释。有没有办法在构造函数输入参数中保留字段的注释?

Class生成构造函数,

@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class Test {

    @Named("MyField")
    private final String field;
    @Named("MyHandler")
    private final SomeHandler handler;
}

生成 class:

public class Test {

    @Named("MyField")
    private final String field;
    @Named("MyField")
    private final SomeHandler handler;

    @Inject
    public Test(final String field, final SomeHandler handler) {
        this.field = field;
        this.handler = handler;
    }
}

想要class:

public class Test {

    @Named("MyField")
    private final String field;
    @Named("MyHandler")
    private final SomeHandler handler;

    @Inject
    public Test(@Named("MyField")final String field, 
                @Named("MyHandler")final SomeHandler handler) {
        this.field = field;
        this.handler = handler;
    }

}

没有这样的功能,看起来没人关心。我proposed it once开始实施,但放弃了(没有需求,工作量太大)。

它可能看起来像

@RequiredArgsConstructor(onConstructor=@__(@Inject))
public class Something {
    @OnConstructor(@Named("userName"))
    private final String userName;

    @OnConstructor(@Named("userPassword"))
    private final String userPassword;

    private final int anotherField;

    private final int yetAnotherField;
}

或者只是

@RequiredArgsConstructor(
     onConstructor=@__(@Inject),
     moveToConstructorArg=@__(@Named))
public class Something {
    @Named("userName")
    private final String userName;

    @Named("userPassword")
    private final String userPassword;

    private final int anotherField;

    private final int yetAnotherField;
}

或者可以使用 lombok.config 进行控制,因为您可能希望将所有 @Named 注释移至构造函数。

恐怕,如果你想要它,那么你必须自己做(我的不完整实现可能会对你有所帮助)。

FTR:现在有 feature request

v1.18.4 版本中,Lombok 添加了对复制特定注释的支持。意思是,如果您将以下设置设为 lombok.config:

lombok.copyableAnnotations += com.google.inject.name.Named

并将以下 Lombok 注释应用到您的 class:

@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class Hello {
    @NonNull @Named("my-name") String name;
}

@Named 注释应复制到生成的构造函数参数中。

局限性:当 annotation can't be put on a field or annotation on a field overrides constructor initialization

时这不起作用