为什么不允许接口作为注释成员? [英] Why are interfaces not allowed as annotation members?

查看:58
本文介绍了为什么不允许接口作为注释成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个代码:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Bar {
    Foo foo() default FooImpl.FooConstant;
}

编译器错误:

注释值不是允许的类型

如果我用 FooImpl 替换 Foo 代码被接受.

If I replace Foo with FooImpl the code is accepted.

这种行为的原因是什么?

What's the reason for this behavior?

推荐答案

如果我用 FooImpl 替换 Foo 代码被接受.

If I replace Foo with FooImpl the code is accepted.

如果编译,我会非常惊讶,除非 FooImpl 是一个枚举.

I would be very surprised if this compiled, unless FooImpl is an enum.

注释成员只能包含以下内容:

Annotation members may only contain the following:

  • 原始类型
  • 字符串
  • 类文字
  • 注释
  • 枚举项
  • 或上述任何一个的一维数组

如果声明的方法的返回类型是编译时错误注释类型是以下之一以外的任何类型:之一原始类型、字符串、类和任何类的调用,一个枚举类型(第 8.9 节)、注释类型或数组(第 10 节)前面的类型.如果有任何方法,它也是一个编译时错误在注解类型中声明的签名是覆盖等效于声明的任何公共或受保护方法的覆盖在类 Object 中或在接口 annotation.Annotation 中.

It is a compile-time error if the return type of a method declared in an annotation type is any type other than one of the following: one of the primitive types, String, Class and any invocation of Class, an enum type (§8.9), an annotation type, or an array (§10) of one of the preceding types. It is also a compile-time error if any method declared in an annotation type has a signature that is override-equivalent to that of any public or protected method declared in class Object or in the interface annotation.Annotation.

来源:JLS

这篇关于为什么不允许接口作为注释成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆