哪些注释目标适用于 Java 记录? [英] What annotation targets are applicable to Java records?

查看:30
本文介绍了哪些注释目标适用于 Java 记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于方法或字段的注释,定义如下:

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

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

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

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 a valid @Target.

以下编译得很好:

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

但是这种带有紧凑构造函数的表单无法使用java:注解类型不适用于这种声明"进行编译.- 这实际上是我所期望的.

But this form with a compact constructor fails to compile with "java: annotation type not applicable to this kind of declaration" - which is actually what I would expect.

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

推荐答案

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

description 可能看起来有点像参数,但就注释定位而言,严格来说并非如此.它也可以充当一个字段.

description may look a bit like a parameter but for the purpose of annotation targeting, it's not strictly just that. It can act like a field too.

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

From the JLS (this version has highlighted the parts which have changed with respect to records):

记录类的记录组件上的注解可能会被传播中指定的记录类的成员和构造函数8.10.3.

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 gist of section 8.10.3 is that annotations such as your @NotColumn are propagated onto the generated methods, fields and parameters only if they are applicable to those targets. They are ignored otherwise. Your annotation is applicable to fields, so it will be propagated to the generated description field of the record.

添加构造函数时出现错误的事实是一个错误 并且已经修复.无论您是否指定构造函数,注释的有效性都应该是相同的.在 Java 的未来版本中,您的两个示例都可以正常编译.

The fact that you get an error when adding a constructor is a bug and has been fixed already. The validity of the annotation was supposed to be the same whether you specify a constructor or not. In future versions of Java, both of your examples will compile fine.

我想阻止用户在记录上使用这个[注释]

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

这不可能,抱歉.

这篇关于哪些注释目标适用于 Java 记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆