Structural search - find any final local variables?

56 Views Asked by At

I'm trying to work with IntelliJ's structural search to find any local variables declared final. I'm using the following:

class $Class$ {
    $ReturnType$ $Method$ ($ParameterType$ $Parameter$) {
        $S$; [0,inf]
        final $Type$ $Name$ = $Init$;
        $St$; [0,inf]
    }
}

This seems to match, for example, as expected:

public static void main (String[] args) {
    System.out.println("Hello world");
    final double q = 1;
}

But it seems to fail on nested statements, for example:

public static void main (String[] args) {
   if (true) {
       final double q = 1;
   }
}

Is there a way to match these within an arbitrary number of nested statements?

1

There are 1 best solutions below

0
Bas Leijdekkers On

Use a template like below. It finds all final variables and checks if they are local using a script modifier.

<searchConfiguration name="p test" text="final $Type$ $var$;" recursive="true" type="JAVA" pattern_context="default" search_injected="false" case_sensitive="true">
  <constraint name="__context__" within="" contains="" />
  <constraint name="Type" within="" contains="" />
  <constraint name="var" script="&quot;var instanceof com.intellij.psi.PsiLocalVariable&quot;" within="" contains="" />
</searchConfiguration>

Depending on your use case, you may also be able to use the "Unnecessary 'final' on local variable or parameter" inspection using Code | Analyze Code | Run Inspection by Name.