2011-12-19 50 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

相關問題