Bjarke Freund-Hansen
Bjarke Freund-Hansen

Reputation: 30128

Java annotation that expands/resolves to many annotations?

I have a set of Java annotation that I quite frequently use, like this:

@SomeAnnotation(Something)
@SomeOtherAnnotation
@SomeLastAnnotation(SomethingElse)
class Foo
{
    /* ... */
}

As I use all these annotations together quite often, and I may have to add to them in everywhere they are used once in a while, I would like to create a new annotation that I can use instead. This annotation should then "resolve" to all the annotations that I define somewhere.

@MySuperAnnotation
class Foo
{
    /* ... */
}

How do I declare @MySuperAnnotation such that it "resolves" to all the other annotations?

Upvotes: 5

Views: 218

Answers (3)

Laurent Legrand
Laurent Legrand

Reputation: 1144

You can do it with AspectJ with the declare annotation instruction: http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations-declare.html

in your context, this should work:

public aspect Declaration {
    declare @type: @MySuperAnnotation *: @SomeAnnotation(Something);
    declare @type: @MySuperAnnotation *: @SomeOtherAnnotation;
    declare @type: @MySuperAnnotation *: @SomeLastAnnotation(SomethingElse);
}

Upvotes: 2

Ahe
Ahe

Reputation: 2124

In general, there is no way. But if you are using spring ( >= 3.0 ) it is possible with custom annotations. Simple example here.

Upvotes: 3

hmakholm left over Monica
hmakholm left over Monica

Reputation: 23332

You can't do that, not without rewriting all of the tools and reflection code that looks for the original annotations.

(Or, as Oliver suggests, you could postprocess the compiled .class files to replace the annotations with something different -- not that I know of any tools that will do that for you automatically).

Upvotes: 0

Related Questions