Skip to content
Advertisement

Why RecordComponent doesn’t have annotation info that is defined in the Records class in Java 17?

I play with records and found something that doesn’t look logical to me:

Record:

JavaScript

Code:

JavaScript

However, if I do:

JavaScript

Is that expected? Because RecordComponent implements AnnotatedElement, so I thought RecordComponent should have info about annotations. Are my expectations wrong?

Advertisement

Answer

This depends on the specified permitted targets of the annotation. The record component has an associated constructor parameter, field, accessor method, and a type. The compiler will accept an annotation if at least one of these locations is permitted, but the annotation will only get associated with the permitted locations of the record.

So the following code

JavaScript

prints

JavaScript

showing how each annotation has been copied to its permitted locations. Only the annotations having RECORD_COMPONENT as permitted target, are retrievable through RecordComponent’s getAnnotation or isAnnotationPresent.

Of course, @Retention(RetentionPolicy.RUNTIME) is also required.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement