intellij-ideastructural-search

Can I use IntelliJ IDEA's Structural Replace to replace varargs with individual method calls?


Basically, I'm calling a now-deprecated Java static method which uses varargs...

MyClass.myMethod(arg1, arg2, arg3...);

...whose usages I need to replace with one that doesn't.

MyClass.myNewMethod(arg1)
    .addArg(arg2)
    .addArg(arg3)
    ...
;

This replacement needs to happen in a large number of places across the code base, and the argument types, values, and code formatting can vary greatly, so a regex replacement isn't really feasible. I'm looking to see if IntelliJ's Structural Replace can help here. I wanted to see if anything like the following was possible:

Search template:

MyClass.myMethod($Arguments$)

Replacement template:

MyClass.myNewMethod(
    for (argument : $arguments$) {
        .addArg(argument)
    }
)

Does IntelliJ IDEA's Structural Search & Replace provide any sort of similar functionality?


Solution

  • Try recursive unrolling. The idea would be to incrementally move the last argument into an addArg call:

    MyClass.myMethod(arg1, arg2, arg3);
    MyClass.myMethod(arg1, arg2).addArg(arg3);
    MyClass.myMethod(arg1).addArg(arg2).addArg(arg3);
    

    So the search template would be:

    MyClass.myMethod($args$, $last$)
    

    (where Count for $args$ = [0, Unlimited])

    The replace template:

    MyClass.myMethod($args$).addArg($last$)
    

    Now repeatedly press Rerun (Ctrl+F5) and Replace All.

    Finally, replace .myMethod with .myNewMethod