我目前定义了此注释:
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
@Beta
public @interface Needs
{
Class<?>[] value();
}
问题是,虽然我可以做到:
@Needs({SomeClass.class, OtherClass.class})
例如,我不能这样做:
@Needs(Map<String, SomeClass>)
目的是对其进行记录并保留如上所述的通用信息。可能吗?
最佳答案
Java 语言规范 writes :
It is a compile-time error if the return type of a method declared in an annotation type is not one of the following: a primitive type, String, Class, any parameterized invocation of Class, an enum type (§8.9), an annotation type, or an array type (§10) whose element type is one of the preceding types.
此限制的原因是注释值在编译时计算,并且仅存储值。因此,这些值不能是任意对象,因为不清楚如何将它们存储在类文件中,并在运行时解码它们。
通常的解决方案是嵌套注释技巧:
public @interface Needs {
Need[] value();
}
public @interface Need {
String key();
Class value();
}
然后你就可以使用它
@Needs([
@Need(key = "aKey", value = A.class)
@Need(key = "anotherKey", value = Another.class)
])
关于java - 如何使@Documented注释保留泛型信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17629883/