Use cases for implementing annotations

Viewed 17615

What are valid use cases for implementing annotations?

When designing primarily annotation based configuration systems I occasionally need to create classes which implement annotations for code generation or programmatic configuration.

The alternative involves mirroring the data contained in annotations into DTOs, which seems like an overhead.

Here is an example:

public enum IDType {
    LOCAL,
    URI,
    RESOURCE;
}

@Documented
@Target( { METHOD, FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Id {
    /**
     * @return
     */
    IDType value() default IDType.LOCAL;
}

with the implementation

public class IdImpl implements Id{

    private final IDType idType;

    public IdImpl(IDType idType){
        this.idType = idType;
    }

    @Override
    public IDType value() {
        return idType;
    }

    @Override
    public Class<? extends Annotation> annotationType() {
        return Id.class;
    }

}

I get compiler warnings for this, but it seems to be a valid tool for many use cases.

The warning for the example above is

The annotation type Id should not be used as a superinterface for IdImpl

Edited :

I just found this example from Guice :

bind(CreditCardProcessor.class)
    .annotatedWith(Names.named("Checkout"))
    .to(CheckoutCreditCardProcessor.class);

See this Javadoc from Names.

Has anyone some information why this restriction exists or has some other use cases in mind?

3 Answers
Related