7

我注意到如果我创建一个注释:

public @interface NullableTypeOverride {
    NullableType hibernateTypeOverride();
}

我对注释属性的选择有限。上面的代码将不起作用,因为注释只采用原始StringClass类型作为它们的属性。

所以在这种情况下,我不能像这样使用这个注释:

@NullableTypeOverride(hibernateTypeOverride = Hibernate.INTEGER)
private Long distance;

我的猜测是它与编译时间与运行时有关,但我不完全确定。那么这个限制的原因是什么,我该如何解决呢?

4

1 回答 1

6

JLS声明

如果在注解类型中声明的方法的返回类型不是以下之一,则为编译时错误:原始类型、字符串、类、对 Class 的任何参数化调用、枚举类型(第 8.9 节)、注解类型或数组类型(第 10 节),其元素类型是上述类型之一。

这样做的原因是注解必须有一个常数值。如果您提供对可能更改的对象的引用,您将遇到问题。这仅在注释的保留为 时才相关RUNTIME

public class Person {
    public String name;
}

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    Person person();
}

@MyAnnotation(person = ???) // how to guarantee it won't change at runtime?
public void method1()  {...}

这个值应该是多少?反射库如何缓存它?

MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
annotation.person(); // should be the same value every time

请记住,注释应该是元数据。

于 2013-09-12T17:10:12.100 回答