Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create structural replace in IDEA to add missing annotation to the class

I'm trying to figure out a Structural replacement template in IntelliJ IDEA (future inspection) for adding a missing annotation to a class/interface/enum without removing any other existing annotations.

So far I tried several varieties of following

Search template:

@$OtherPossibleAnnotation$ // min: 0, max: 0, text/regexp: AnnotationName, invert condition: true
@$MissingAnnotation$ // min: 0, max: 0, text/regexp: AnnotationName
class $C$ {
    $Content$ // min: 0, max: unlimited
}

Replacement template:

@$OtherPossibleAnnotation$
@AnnotationName
class $C$ {
    $Content$
}

But none of my attempts worked. I expect it to work

  • with any set of existing class annotations and it must also keep their potential values,
  • if there is no annotation on the class at all,
  • in Idea 14 as well as in Idea 15,
  • should also keep content of the class untouched.

So for instance following

@ProductArea("Area A")
class A {
    public void method1() {
        System.out.println("Should remain");
    }
}

should be replaced with

@ProductArea("Area A")
@AnnotationName
class A {
    public void method1() {
        System.out.println("Should remain");
    }
}

Could someone please advise?

like image 651
imparente Avatar asked Nov 16 '15 16:11

imparente


1 Answers

The following works for me in IntelliJ IDEA 2019.3 EAP.

Search Template:
@$MissingAnnotation$ // count=[0,0], text=AnnotationName
class $C$ {
}
Replace Template
@AnnotationName
class $C$ {
}

This will keep existing annotations and class content, but only when using IntelliJ IDEA 2019.3 EAP

To save some manual editing, copy the following to your clipboard and use "Import Template from Clipboard" under the cog menu in the Structural Search dialog:

<replaceConfiguration name="method calls" text="@$MissingAnnotation$ &#10;class $C$ {&#10;}" recursive="false" caseInsensitive="true" type="JAVA" pattern_context="default" reformatAccordingToStyle="false" shortenFQN="true" replacement="@AnnotationName&#10;class $C$ {&#10;}">
  <constraint name="__context__" within="" contains="" />
  <constraint name="MissingAnnotation" regexp="AnnotationName" minCount="0" maxCount="0" within="" contains="" />
  <constraint name="C" within="" contains="" />
</replaceConfiguration>
like image 64
Bas Leijdekkers Avatar answered Oct 15 '22 13:10

Bas Leijdekkers