在 Scala 中注释构造函数参数 [英] Annotating constructor parameters in Scala
问题描述
在编译为字节码时,注释构造函数参数似乎没有任何作用.我也没有收到编译器警告.
Annotating constructor parameters seems to do nothing when compiled to bytecode. I get no compiler warnings either.
以下有效.name
字段的 getAnnotations
返回 javax.annotation.Nullable
.
The following works. getAnnotations
for the name
field returns javax.annotation.Nullable
.
class Person {
@Nullable var name: String = _;
}
以下不是,无论是 val
还是 var
.
The following doesn't, neither with val
or var
.
class Person(@Nullable var name: String)
这可能不是故意的,所以是我遗漏了什么还是应该提交错误报告?
This is probably not intentional, so is there something I am missing or should I go file a bug report?
推荐答案
当您在构造函数参数上指定注释时,您需要指定应该注释的内容.
You need to specify what should get annotated when you specify annotations on constructor parameters.
为此,使用来自 scala.annotation.target
的一个或多个注释来注释您的注释,例如getter
、setter
或在您的情况下 field
:
To do that annotate your annotation with one ore more annotations from scala.annotation.target
, e.g. getter
, setter
or as in your case field
:
import annotation.target.field
class Person(@(Nullable @field) var name: String)
您也可以为此使用类型别名:
You can also use type aliases for that:
type NullableField = Nullable @field
class Person(@NullableField var name: String)
更新 Scala 2.12
现在这个特定的注解和其他注解在 scala.annotation.meta 包中,而不是 scala.annotation.target
Update Scala 2.12
Now this specific annotation and others are in the package scala.annotation.meta rather than scala.annotation.target
import scala.annotation.meta.{field, param}
这篇关于在 Scala 中注释构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!