2014-03-02 156 views
18

在項目中,我使用預先定義的註釋@With如何擴展Java註釋?

@With(Secure.class) 
public class Test { //.... 

@With的源代碼:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE) 
public @interface With { 

    Class<?>[] value() default {}; 
} 

我想編寫自定義註釋@Secure,它會自動將Secure.class@With註解。怎麼做?


如果我這樣做?它會起作用嗎?

@With(Secure.class) 
@Target({ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Secure { 

} 

回答

11

從Java語言規範,Chapter 9.6 Annotation Types

沒有擴展條款是允許的。 (註釋類型隱式擴展爲annotation.Annotation。)

因此,不能擴展註釋。您需要使用其他一些機制或創建一個識別和處理您自己的註釋的代碼。 Spring允許您在自己的自定義註釋中對其他Spring的註釋進行分組。但仍然沒有延伸。

+0

可能'擴展'並不是最好的表達。我的意思是實施自動放置參數。 – bvitaliyg

+0

@bvitaliyg:您可以使用任何默認字段創建自己的註釋,但是jvm中沒有可以自動識別它的開箱即用機制。您需要自己編寫該代碼或檢查現有庫(如spring)是否足以滿足您的需求 – piotrek

+0

這不是Spring框架。 – bvitaliyg

9

正如piotrek所指出的那樣,您不能在繼承的意義上擴展Annotations。不過,你可以創建一個聚集他人註解:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.TYPE}) 
public @interface SuperAnnotation { 
    String value(); 
} 

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.TYPE}) 
public @interface SubAnnotation { 
    SuperAnnotation superAnnotation(); 
    String subValue(); 
} 

用法:

@SubAnnotation(subValue = "...", superAnnotation = @SuperAnnotation(value = "superValue")) 
class someClass { ... } 
0

如何製作Secure標註有默認value()

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE) 
public @interface Secure { 

    Class<?>[] value() default { Secure.class }; 
} 
0
@With(Secure.class) 
@Target({ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Secure { 

} 

這將工作。

+0

這是直接從問題中直接複製。 – mkobit

+0

@mkobit斑點。由於提問者詢問這是否適用於他們的問題,我的回答就直截了當地回答了問題。 –

0

爲了擴展穆罕默德·阿卜杜勒 - 拉赫曼的answer--

@With(Secure.class) 
@Target({ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME) 
public @interface Secure { 

} 

這確實默認的工作,但你可以結合Spring的AnnotationUtils使用它。

查看this SO answer舉例。