如何在自定义注解中使用类类型的成员?

huangapple go评论65阅读模式
英文:

How to use a member of Class type in custom annotation?

问题

我尝试将其定义如下:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Validate {
    Class<?> check() default MyClass.class;
}

我在这里收到错误消息:注解成员的类型无效 'MyClass'。

有人能帮忙解决吗?

英文:

Im new to java custom annotations and trying to define a member of type MyClass in my custom java annotation.

I tried to define it as follows:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Validate {
    MyClass check() default MyClass.class;
}

I get error here: Invalid type 'MyClass' for annotation member.

Could anyone help to solve this.

答案1

得分: 1

你不能轻松地将自定义类用作注解成员,除非该类是 enum。因此,如果 MyClass 不是 enum,那么它就不能被使用。

你可以在Java 17 语言规范 §9.6.1 注解接口元素中找到更多信息。

在注解接口主体中声明的方法的返回类型必须是以下之一,否则将出现编译时错误:

基本数据类型

字符串

类或 Class 的调用(§4.5)

枚举类类型

注解接口类型

其组件类型为前述类型之一的数组类型(§10.1)

因此,只有当 MyClassenum 或其类型为 Class<MyClass> 时,才能使用它。

英文:

You cannot use a custom class easily as an annotation member unless such a class is an enum. So if MyClass is not an enum, then it cannot be used.

You can find more information in the Java 17 Language Specification $9.6.1 Annotation Interface Elements.

> The return type of a method declared in the body of annotation interface must be one of the following, or a compile-time error occurs:
>
> A primitive type
>
> String
>
> Class or an invocation of Class (§4.5)
>
> An enum class type
>
> An annotation interface type
>
> An array type whose component type is one of the preceding types (§10.1).

Therefore MyClass can be used only if it is an enum or it's type as Class&lt;MyClass&gt;.

huangapple
  • 本文由 发表于 2023年3月8日 15:13:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定