java - 如何使@Documented注释保留泛型信息?

标签 java generics annotations

我目前定义了此注释:

@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/

相关文章:

iPhone map 查看: Annotation Pin - Different Color

java - 更改 session 变量而不重新加载页面

java - 指定权重的boxcar平均算法

java - 使用 Oracle 的 Spring Boot 2.0 分页不起作用

具有动态 Func<> 构造的 C# Fluent API

java - 只接受部分类的通用方法

java - 通用编程有必要吗?

java - 在字符串之间创建一个新行

java - Java 注释的最佳(或至少是好的)指南

java - 在运行时访问注解