将注释值设置为 Class<?> 时出错从一个常数,为什么?

Error setting annotation value as Classlt;?gt; from a constant, why?(将注释值设置为 Class? 时出错从一个常数,为什么?)
本文介绍了将注释值设置为 Class<?> 时出错从一个常数,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

这是我的注释:

@Target( { ElementType.METHOD } )
@Retention(RetentionPolicy.RUNTIME)
public @interface AuditUpdate
{
    Class<?> value();
}

这样就可以了:

@AuditUpdate(User.class)
void someMethod(){}

但是通过这种方式:

private static final Class<?> ENTITY_CLASS = User.class;
@AuditUpdate(ENTITY_CLASS)
void someMethod(){}

我有这个编译错误:

The value for annotation attribute AuditUpdate.value must be a class literal

为什么?这是什么意思?

Why? What does that mean?

谢谢.

推荐答案

这意味着你必须传递一个类字面量,而不是一个变量(即使是常量).

It means that you must pass a class literal, rather than a variable (even if constant).

类文字在 JLS:

15.8.2 类文字

类字面量是由类名组成的表达式,接口、数组或原始类型,后跟."和令牌班级.类文字的类型是 Class.它评估为类由定义定义的命名类型(或 void)的对象当前实例的类的类加载器.

A class literal is an expression consisting of the name of a class, interface, array, or primitive type followed by a `.' and the token class. The type of a class literal is Class. It evaluates to the Class object for the named type (or for void) as defined by the defining class loader of the class of the current instance.

所以,你不能那样做.

这篇关于将注释值设置为 Class<?> 时出错从一个常数,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)