Home > Mobile >  Replacing Type with var for all 'Class class = new Class()' usages in Java project
Replacing Type with var for all 'Class class = new Class()' usages in Java project

Time:10-04

I recently switched to Java 11 for a rather big project, and would like to switch to using var class = new Class() instead of Class class = new CLass().

I tried using Intellij Structural Search (and replace) for this, but its turning out to be more complex than expected.

My first attempt was $Type$ $Inst$ = new $Constructor$($Argument$);, which also matches global variables (which don't allow var).

My second attempt is:

class $Class$ {
  $ReturnType$ $Method$ ($ParameterType$ $Parameter$) throws $ExceptionType$ {
      $Statements$;
      final $Type$ $Inst$ = new $Constructor$($Argument$);
      $Statements2$;
  }
}

Which misses all calls inside e.g. try blocks (since they get matched by the expressions)

Any help would be greatly appreciated!

CodePudding user response:

Use your first template

$Type$ $Inst$ = new $Constructor$($Argument$);

But add a Script modifier on the $Inst$ variable with the following text:
Inst instanceof com.intellij.psi.PsiLocalVariable

Alternatively you may want to try the Local variable type can be omitted inspection that is available in IntelliJ IDEA.

  • Related