Intellij structural replace change method signature

1.6k views Asked by At

I'd like to change a method with a certain signature:

public OldReturnType get.*(Params) {
  //lots of code
}

to this:

public NewReturnTyp get.*(Params) {
  //lots of code
}

-> I'd like to replace the return type. I tried this with SSR:

  • Copy existing Template "methods of the class". This yields the template:

    class $Class$ { $ReturnType$ $MethodName$($ParameterType$ $Parameter$); }

I first tried to replace $ReturnType$ OldType and NewType respectivly:

Search Template:

class $Class$ { 
  OldType $MethodName$($ParameterType$ $Parameter$);
}

Replace Template:

class $Class$ { 
  NewType $MethodName$($ParameterType$ $Parameter$);
}

This gives me all the methods, but if I replace it, the method gets removed.

I then tried to changed the pattern the following way:

Search Template:

class $Class$ { 
  $OldType$ $MethodName$($ParameterType$ $Parameter$);
}

And specified, that $OldType$ should be the target of the search. I also specified a RegEx pattern: OldType for this variable.

Replace Template:

class $Class$ { 
  NewType $MethodName$($ParameterType$ $Parameter$);
}

This also finds all the methods but they get removed if I replace. I tried very different, always with the same result: The method gets removed if I replace the match. How do I have to specify the search/replace Template to just replace OldType with NewType in the signature.

1

There are 1 answers

4
Bas Leijdekkers On BEST ANSWER

You have encountered a bug in Structural Search & Replace. Probably this one: https://youtrack.jetbrains.com/issue/IDEA-127835

But there is a workaround. Use the following Search Template:

class $Class$ { 
  OldType $MethodName$($ParameterType$ $Parameter$) {
    $statement$;
  }

  $other$;
}

Make sure "This variable is target of the search" for $MethodName$ is NOT set, or it won't work.

$statement$
minimum count: 0
maximum count: unlimited

$other$
minimum count: 0
maximum count: unlimited

The rest as in the methods of the class existing template.

Replacement Template as you would expect is the same as the Search Template, only with NewType replacing OldType.

Let me know if it works, or if you have any more problems.