javaintellij-ideaannotationsstructural-search

How to structurally replace value of one parameter of an annotation in IntelliJ


I have classes annotated with @SequenceGenerator(name = "seq_gen",/*other_parameters*/) I need to replace "seq_gen" with "$Class$_seq_gen" in each class.

I've tried following.

Search

@SequenceGenerator(name = "seq_gen")
class $Class$ {}

Replacement

@SequenceGenerator(name = "$Class$_seq_gen")
class $Class$ {}

When I run the replacement the /*other_parameters*/ part gets removed.

I also tried

Search

@SequenceGenerator(name = "$VALUE$")
class $Class$ {}

Replacement

"$Class$_$VALUE$"

with $VALUE$ as target, it does not remove anything now but replaces with _seq_gen as if $Class$ was not defined.

How can I accomplish this? Documentation of SSR is quite confusing and not detailed.


I've found this question through search on SO, but it doesn't have and actual answer and is really about issue with arrays. Replace one of annotation parameters with IntelliJ IDEA's Structural replace


Solution

  • This used to be difficult to accomplish because of a bug in Structural Search relating to annotation parameters. This bug has been fixed. Currently you can use the first suggestion in the question:

    Search template:

    @SequenceGenerator(name = "seq_gen")
    class $Class$ {}
    

    Replacement template:

    @SequenceGenerator(name = "$Class$_seq_gen")
    class $Class$ {}
    

    Old workaround

    Previously a workaround was needed, which used a replacement variable and Groovy script. Like the following search template:

    @SequenceGenerator(name = $value$)
    class $Class$ {}
    

    $value$ constraints

    text/regexp: "seq_gen" (including quotes)
    This variable is target of the search: enabled

    Replacement template:

    $replacement$
    

    $replacement$ script constraints

    script text:

    import com.intellij.psi.util.PsiTreeUtil
    import com.intellij.psi.PsiClass
    
    def x = PsiTreeUtil.getParentOfType(value, PsiClass.class);
    "\"" + x.name + "_seq_gen\""