简体   繁体   中英

How to use annotation in an annotation?

Given:

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

in Java 7 is it possible to do something like:

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

?

You can. This is an example from Jackson library (leaving out the comments):

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 "";
    }
}

And here is an example usage:

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

How to use annotation in an annotation?

Maybe like this

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

    public MyAnnotation[] refine();
}

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

Also, in Java 8, you can have Repeatable annotations - so you may refine or add to your 'primary' (eg the first) other refinements brought in by subsequent repetitions of the same annotation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM