mardi 13 avril 2021

Java Record confusion with Annotations with fields vs parameters?

I spotted an oddity today testing out record support for my Persism ORM Library.

I have an annotation used for methods or fields defined like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD, ElementType.FIELD})
public @interface NotColumn {
}

I wanted to prevent users from using this on a record since it wouldn't make sense for this annotation to be used in that context. It seems doing this should not compile since I don't specify ElementType.PARAMETER as valid Target.

The following compiles fine though:

public record MyRecord(String customerId,
                       String companyName,
                       @NotColumn String description
}

But this form with a compact constructor

public record MyRecord(String customerId,
                       String companyName,
                       @NotColumn String description

   public MyRecord {
   }

}

Fails to compile with "java: annotation type not applicable to this kind of declaration" - which is actually what I would expect.





Aucun commentaire:

Enregistrer un commentaire