Lombok misses field's annotation while auto generating constructor. Is there a way to retain field's annotation in constructor input params?
Class to generate constructor,
@RequiredArgsConstructor(onConstructor = @__(@Inject)) public class Test { @Named("MyField") private final String field; @Named("MyHandler") private final SomeHandler handler; }
Generated 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; } }
Desired 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; } }
But if you add a constructor with parameters (or @AllArgsConstructor ), then you'll need to add a no args constructor (or @NoArgsConstructor ) as well, for JPA/Hibernate to work.
@NoArgsConstructor will generate a constructor with no parameters. If this is not possible (because of final fields), a compiler error will result instead, unless @NoArgsConstructor(force = true) is used, then all final fields are initialized with 0 / false / null .
The @Value annotation is one of the annotations from Project Lombok that is added to Java classes to make them and their instances immutable. Immutable is just fancy word for non-changeable. This means that immutable objects cannot have their fields changed once they are initialized.
Also, I really discourage using any Lombok annotation that modifies the code. If you take @Data, @Getter, @Setter, @AllArgsConstructor adds new codes into the existing source code without modifying the code we wrote.
In version v1.18.4 Lombok added support for copying specific annotations. Meaning, that if you put following setting to lombok.config
:
lombok.copyableAnnotations += com.google.inject.name.Named
and apply following Lombok annotations to your class:
@RequiredArgsConstructor(onConstructor = @__(@Inject)) public class Hello { @NonNull @Named("my-name") String name; }
the @Named
annotation should be copied to your generated constructor argument.
Limitations: this does not work when annotation can't be put on a field or annotation on a field overrides constructor initialization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With