2016-09-22 243 views
2

考虑:如何在注释中使用注释?

public @interface MyAnnotation(){ 
    public SomeType[] value(); 
} 

在Java 7中是有可能做这样的事情:

@MyAnnotation({ 
    value1, 
    @MyAnnotation({subValue1, subvalue2, ...}) value2, 
    ... 
    valueN 
}) 
public Object someProperty; 

+0

您是否打算创建一个框架来使用它? –

+0

MyAnnotation是否来自SomeType? (对,我不这么认为)。那么你想如何创建一个'SomeType'数组,其中包含一个不是'SomeType'类型的元素? –

+0

@TimBiegeleisen是的。 – Sayid

回答

-1

你可以。这是Jackson库(而忽略了评论)一个例子:

package com.fasterxml.jackson.annotation; 

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 

@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.FIELD, 
    ElementType.METHOD, ElementType.PARAMETER}) 
@Retention(RetentionPolicy.RUNTIME) 
@JacksonAnnotation 
public @interface JsonSubTypes { 
    public Type[] value(); 

    public @interface Type { 
     /** 
     * Class of the subtype 
     */ 
     public Class<?> value(); 

     /** 
     * Logical type name used as the type identifier for the class 
     */ 
     public String name() default ""; 
    } 
} 

而且这里有一个例子用法:

@JsonSubTypes({ 
     @JsonSubTypes.Type(value = TestSystemEvent.class, name = "TestEvent"), 
}) 
public interface SystemEvent { 
} 
+1

这只是解释了如何多次使用相同的注释。不完全符合我的问题。此外,彼此使用的注释是不同的。 'JsonSubTypes'中使用的'JsonSubTypes.Type'。 – Sayid

+0

注解被认为是元数据。它们不是对象,所以它们不会与String等其他实例共享相同的祖先Object。 – mtyurt

-1

How to use annotation in an annotation?

也许这样

public @interface MyAnnotation(){ 
    public SomeType[] value(); 

    public MyAnnotation[] refine(); 
} 

@MyAnnotation(
    {value1, value2}, 
    refine={ @MyAnnotation({valueX, valueY}), @MyAnnotation(valueM) } 
) 
public Object someProperty; 

另外,在Java 8中,您可以拥有Repeatable注释tions - 所以你可以改进或添加到你的'主'(例如第一次)通过后续重复的相同注释带来的其他改进。

+1

这给编译器错误:'循环注释元素类型' – Sayid

+0

好吧,正如我所说...“也许”。回到可重复。或创建另一个具有类似价值的注释 –