java记录上的构造函数注释
有没有办法获得像ConstructorProperties这样的注释,它@Target(CONSTRUCTOR)必须注释 java 16 记录的生成构造函数?例如:
@ConstructorProperties({"id", "filename"})
public record Person(long id, String filename) {}
此 ^ 导致以下错误:
java: annotation type not applicable to this kind of declaration
回答
这有效:
public record Person(long id, String filename) {
@ConstructorProperties({"id", "filename"})
public Person {}
}
我的理解是,没有参数列表的内部构造函数是向使用组件列表创建的默认构造函数添加逻辑的一种方式。显然,向其添加构造函数注释具有我所追求的最终结果:)
- 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.
- It would be even better, if the Java Beans gets an update to recognize records, eliminating the need for the `@ConstructorProperties` annotation…
- @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.)