Constructor annotation on java records
Asked Answered
J

1

12

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
Johnsen answered 19/4, 2021 at 20:2 Comment(0)
J
15

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 :)

Johnsen answered 19/4, 2021 at 20:2 Comment(4)
Yes, this is the recommended solution. The syntactic form you describe is called a compact constructor; it is a concise way of declaring the canonical constructor of a record, which is the constructor whose argument list matches that of the record.Accede
It would be even better, if the Java Beans gets an update to recognize records, eliminating the need for the @ConstructorProperties annotation…Hydroid
@BrianGoetz are you sure? I’ve read openjdk.java.net/contribute and get a different impression. For an outsider, it’ll take an hour to implement and weeks for trying to get it into the JDK…Hydroid
@Hydroid The first few times will take longer, for sure. And yes, the non-code aspects can overshadow the code aspects -- and this is true for my job too. But that's just what "contribute" means at the scale of Java -- the code is only a small part of the work. (So yes, contributions are welcome, but "here's my code" is not the contribution most people think it is.)Accede

© 2022 - 2024 — McMap. All rights reserved.