Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor annotation on java records

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
like image 206
pearcemerritt Avatar asked Apr 19 '21 20:04

pearcemerritt


People also ask

Can records have constructors?

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.

Does Lombok work with records?

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.

What is canonical constructor in Java?

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.

What Are records in Java 17?

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.


1 Answers

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

like image 198
pearcemerritt Avatar answered Oct 23 '22 00:10

pearcemerritt