Is there a way to get an annotation like ConstructorProperties that has @Target(CONSTRUCTOR)
to annotate the generated constructor of a java 16 record? E.g.:
@ConstructorProperties({"id", "filename"})
public record Person(long id, String filename) {}
This ^ causes the following error:
java: annotation type not applicable to this kind of declaration
If you want your record's constructor to do more than initialize its private fields, you can define a custom constructor for the record. However, unlike a class constructor, a record constructor doesn't have a formal parameter list; this is called a compact constructor.
Lombok enables you to use @EqualsAndHashCode. Exclude for excluding components from the hashCode and equals method generation. To achieve the equivalent currently with Records, you should re-implement hashCode and equals yourself.
The compiler also creates a constructor for you, called the canonical constructor. This constructor takes the components of your record as arguments and copies their values to the fields of the record class. There are situations where you need to override this default behavior.
More information about records, including descriptions of the implicitly declared methods synthesized by the compiler, can be found in section 8.10 of The Java Language Specification . A record class is a shallowly immutable, transparent carrier for a fixed set of values, called the record components.
This worked:
public record Person(long id, String filename) {
@ConstructorProperties({"id", "filename"})
public Person {}
}
My understanding is that the inner constructor with no parameter list is a way of adding logic to the default constructor created using the component list. Apparently, adding a constructor annotation to that has the end result I was after :)
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