哪些类型可用于Java注释成员?

时间:2009-09-22 07:06:06

标签: java annotations

今天我想在this documentation之后创建我的第一个注释界面,我得到了编译器错误

Invalid type for annotation member":
public @interface MyAnnotation {
    Object myParameter;
    ^^^^^^
}

显然Object不能用作注释成员的类型。不幸的是,我找不到任何关于哪些类型可以使用的信息。

我发现这是使用反复试验:

  • String→有效
  • int→有效
  • Integer→无效(令人惊讶)
  • String[]→有效(令人惊讶)
  • Object→无效

也许有人可以了解实际允许哪些类型以及原因。

4 个答案:

答案 0 :(得分:275)

section 9.6.1 of the JLS指定。注释成员类型必须是以下之一:

  • 原始
  • 字符串
  • 一个Enum
  • 另一个注释
  • 上述
  • 中的任何一个的数组

这似乎有限制,但毫无疑问有理由。

另请注意,上述规则隐式禁止使用多维数组(例如String[][])。

答案 1 :(得分:57)

我同意Skaffman的可用类型。

附加限制:它必须是编译时常量

例如,禁止以下内容:

@MyAnnot("a" + myConstantStringMethod())
@MyAnnot(1 + myConstantIntMethod())

答案 2 :(得分:22)

另外,请不要忘记注释本身可以是注释定义的一部分。这允许一些简单的注释嵌套 - 在您希望多次出现一个注释的情况下很方便。

例如:

@ComplexAnnotation({
    @SimpleAnnotation(a="...", b=3),
    @SimpleAnnotation(a="...", b=3),
    @SimpleAnnotation(a="...", b=3)
})
public Object foo() {...}

其中SimpleAnnotation

@Target(ElementType.METHOD)
public @interface SimpleAnnotation {
    public String a();
    public int b();
)

ComplexAnnotation

@Target(ElementType.METHOD)
public @interface ComplexAnnotation {
    public SimpleAnnotation[] value() default {};
)

示例来自:https://blogs.oracle.com/toddfast/entry/creating_nested_complex_java_annotations

答案 3 :(得分:11)

注释的概念非常适合我的项目设计,直到我意识到注释中不能有复杂的数据类型。我通过使用我想要实例化的类而不是该类的实例化对象来解决它。它并不完美,但java很少。

@interface Decorated { Class<? extends PropertyDecorator> decorator() }

interface PropertyDecorator { String decorate(String value) }

class TitleCaseDecorator implements PropertyDecorator {
    String decorate(String value)
}

class Person {
    @Decorated(decorator = TitleCaseDecorator.class)
    String name
}
相关问题