Java 注解 - 如何创建数组?

aer*_*ion 5 java annotations

我尝试使用嵌套的 JAVA 注释创建“地图”。

public @interface EnvInstance {
    Env env();
    Instance instance();
}

public @interface Configuration {
    String description();
    EnvInstance[] envInstances() default {};
}

@Configuration(description = "Test", envInstances = {
    @EnvInstance(env = Env.CERT, instance = Instance.FIRST),
    @EnvInstance(env = Env.INTEGR, instance = Instance.SECOND),
    @EnvInstance(env = Env.PROD, instance = Instance.FIRST),
    ...
}
)
public class TestObject {

}
Run Code Online (Sandbox Code Playgroud)

它似乎有效,但有一件事我不知道如何实现。我想创建两组默认envInstances配置,以便我可以键入:

@Configuration(description = "Test", envInstances = SET_ONE)
public class TestObject {
}
Run Code Online (Sandbox Code Playgroud)

或者

@Configuration(description = "Test", envInstances = SET_TWO)
public class TestObject {
}
Run Code Online (Sandbox Code Playgroud)

是否有可能创建内部注释的静态数组或类似的东西并将其传递给外部注释?

Jar*_*lak 2

恐怕没有办法提取这个重复项。

您不能从常量向注释提供数组值(了解更多)。也不可能创建扩展另一个注释的注释(了解更多)。

我不知道上下文,但是您是否考虑过将此信息传递到对象本身,并将其存储为字段,而不是通过注释?

另一个可能有效的潜在解决方案是让这些类实现标记接口并注释接口。然而,注释不会被继承。如果您可以修改解析器(或任何正在读取注释的内容),您可以执行以下操作:

@Retention(RetentionPolicy.RUNTIME)
public @interface X {
    String[] value();
}

@X({"a", "b", "c"})
interface AnInterface {}

public static class TestClass implements AnInterface {}

public static void main(String[] args) {
    // annotations are not inherited, empty array
    System.out.println(Arrays.toString(TestClass.class.getAnnotations()));

    // check if TestClass is annotated with X and get X.value()
    Arrays.stream(TestClass.class.getAnnotatedInterfaces())
            .filter(type -> type.getType().equals(AnInterface.class))
            .map(type -> (Class<AnInterface>) type.getType())
            .findFirst()
            .ifPresent(anInterface -> {
                String[] value = anInterface.getAnnotation(X.class).value();
                System.out.println(Arrays.toString(value));
            });
}
Run Code Online (Sandbox Code Playgroud)