哪些注释目标适用于 Java 条记录?

What annotation targets are applicable to Java records?

我有一个注释用于这样定义的方法或字段:

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

我想阻止用户在记录中使用这个,因为在那个上下文中使用这个注释是没有意义的。这样做似乎不应该编译,因为我没有将 ElementType.PARAMETER 指定为有效的 @Target.

尽管以下编译正常:

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

但是这种带有紧凑构造函数的形式无法通过“java: 注释类型不适用于这种声明”进行编译——这实际上是我想要的期待。

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

description 可能看起来有点像参数,但出于注解定位的目的,strictly 并非如此。它也可以像一个领域一样。

来自the JLS(此版本突出显示了与记录相关的更改部分):

Annotations on a record component of a record class may be propagated to members and constructors of the record class as specified in 8.10.3.

第 8.10.3 节的要点是,只有当它们适用于那些目标时,@NotColumn 等注释才会传播到生成的方法、字段和参数 ].否则它们将被忽略。您的注释适用于字段,因此它将传播到记录的生成的 description 字段。

The fact that you get an error when adding a constructor is a bug 并且已经修复。无论您是否指定构造函数,注释的有效性都应该是相同的。在 Java 的未来版本中,您的两个示例都可以正常编译。

I wanted to prevent users from using this [annotation] on a record

不可能,抱歉。