gMale
gMale

Reputation: 17895

AspectJ: How to replace an existing annotation

Using AspectJ, how do you replace an existing annotation?

I have the following code

declare @method : @Test * *(..) : @Test(timeout=10);

Which generates the following error on every test method:

... already has an annotation of type org.junit.Test, cannot add a second
instance [Xlint:elementAlreadyAnnotated]

Of course, the error makes sense but what is the syntax to say, "remove the @Test annotation from all methods that have it. Then replace it with @Test(timeout=10)"

Upvotes: 1

Views: 1637

Answers (2)

Andy Clement
Andy Clement

Reputation: 2560

I'm the AspectJ project lead. Under https://bugs.eclipse.org/bugs/show_bug.cgi?id=313026 we are looking at how to use declare annotation for:

  • augmenting existing annotations (adding values to those that are already there)
  • replacing them
  • defining precedence (should your declare replace what is there?)

We are also looking at a form of it that removes annotations:

declare @remove_from_method: int mymethod(): @ToBeRemoved;

But you can't do it yet...

Upvotes: 4

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

I doubt that you can do that with AspectJ. At least I could not find any relevant info in the current version of AspectJ in Action.

What you can do is inject your own custom annotation next to the test annotation and write a custom JUnit Runner class (bound with the @RunWith annotation, which you can again inject with your aspect) that gives your custom annotation precedence over the @Test annotation.

Upvotes: 1

Related Questions