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

1 Answer 1

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

4
  • 6
    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. Commented Apr 19, 2021 at 21:39
  • 2
    It would be even better, if the Java Beans gets an update to recognize records, eliminating the need for the @ConstructorProperties annotation…
    – Holger
    Commented Apr 20, 2021 at 9:02
  • @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…
    – Holger
    Commented Apr 21, 2021 at 8:15
  • 3
    @Holger 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.) Commented Apr 21, 2021 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.