这取决于注释的指定允许目标。记录组件具有关联的构造函数参数、字段、访问器方法和类型。如果允许这些位置中的至少一个,编译器将接受注释,但注释只会与记录的允许位置相关联。
所以下面的代码
public class RecordAnnotations {
public static void main(String[] args) {
Class<?> cl = Test.class;
for(var r: cl.getRecordComponents()) {
System.out.println("record component "
+ Arrays.toString(r.getAnnotations()) + " " + r);
System.out.println("\tof type " + r.getAnnotatedType());
System.out.println("\taccessed by " +
Arrays.toString(r.getAccessor().getAnnotations())+" "+r.getAccessor());
System.out.println("\twith return type "
+ r.getAccessor().getAnnotatedReturnType());
}
System.out.println();
for(var r: cl.getDeclaredFields()) {
System.out.println("field " + Arrays.toString(r.getAnnotations())+" "+r);
System.out.println("\tof type " + r.getAnnotatedType());
}
System.out.println();
for(var c: cl.getDeclaredConstructors()) {
System.out.println("constructor " + c);
for(var r: c.getParameters()) {
System.out.println("\tparameter "
+ Arrays.toString(r.getAnnotations()) + " " + r);
System.out.println("\t\tof type " + r.getAnnotatedType());
}
}
//System.out.println();
//for(var r: cl.getRecordComponents()) System.out.println(r);
}
}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.RECORD_COMPONENT)
@interface WithRecord {}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD)
@interface WithField {}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER)
@interface WithParameter {}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE)
@interface WithTypeUse {}
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD)
@interface WithMethod {}
record Test(@WithRecord @WithField @WithParameter @WithTypeUse @WithMethod
int component) {
}
印刷
record component [@WithRecord()] int component
of type @WithTypeUse() int
accessed by [@WithMethod()] public int Test.component()
with return type @WithTypeUse() int
field [@WithField()] private final int Test.component
of type @WithTypeUse() int
constructor Test(int)
parameter [@WithParameter()] int component
of type @WithTypeUse() int
显示如何将每个注释复制到其允许的位置。只有具有RECORD_COMPONENT
允许目标的注释才能通过RecordComponent
'sgetAnnotation
或isAnnotationPresent
.
当然,@Retention(RetentionPolicy.RUNTIME)
也是必须的。