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

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

问题描述

考虑这个code:

  @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
公共@interface酒吧{
    富富()默认FooImpl.FooConstant;
}

编译器错误:


  

注释值不是允许的类型


如果我更换 FooImpl 的code被接受。

什么是对这种行为的原因是什么?


解决方案

  

如果我FooImpl更换美孚的code被接受。


我会感到非常惊讶,如果这编译,除非FooImpl是一个枚举。

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


  • 原始类型

  • 字符串

  • 类的文字

  • 注释

  • 枚举项

  • 上述任何
  • 的或一维数组

  

这是一个方法的返回类型中声明编译时错误
  注释类型比以下之外的任何类型:一
  原始类型,字符串,阶级和阶级的任何调用,一个
  枚举类型(§8.9),注释类型,或中的一个的一个数组(§10)
  preceding类型。这也是如果有方法的编译时错误
  在注释类型声明有一个签名是
  否决相当于声明的任何公共或受保护的方法
  在Object类或接口annotation.Annotation。


来源: JLS

Consider this code:

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

Compiler error:

annotation value not of an allowable type

If I replace Foo with FooImpl the code is accepted.

What's the reason for this behavior?

解决方案

If I replace Foo with FooImpl the code is accepted.

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

Annotation members may only contain the following:

  • primitive type
  • String
  • Class literal
  • annotation
  • enum item
  • or 1-dimensional arrays of any of the above

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.

Source: JLS

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

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