2011-12-19 54 views
2

这是我的注解:将常量中的注释值设置为<?>类时出错,为什么?

@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 

W HY?那是什么意思?

谢谢。

回答

5

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

类文本在JLS是明确界定:

15.8.2 Class Literals

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.

所以,你不能这样做。

+0

好的,谢谢。 ¿那是什么原因?它很烦人。 – francadaval 2011-12-19 17:39:54

+4

@francadaval - 注解的信息在编译时被解析,你正在做的事情需要静态初始化来运行,以确定类的值。要把它变为极端 - 如果你有:... ENTITY_CLASS = pick_my_class();代替?现在,编译器不得不神奇地知道会返回什么。他们决定只允许文字,因为编译器可以简单地解决它。 – James 2011-12-19 18:30:38

+0

很好的解释,非常感谢。 – francadaval 2011-12-20 12:30:57

相关问题