Search code examples
intellij-ideastructural-search

IntelliJ IDEA: How to create a new class field during Structural replace


I have many calls to static class method

E.g.

LegacyLogger.println (ERROR_LEVEL, "Simple string parameter");

I have found all the needed code occurrences by using the template:

LegacyLogger.println(ERROR_LEVEL, $params$)

How can I possibly import class and create a new field

Logger logger = Logger.GetInstance(SomeClass.class);

inside classes after replacing this search string with:

logger.error("Simple string parameter");

Solution

  • You could try a regular Find in Path search for something like "logger." and open the result in a Find window. This should find all source files where you are using the new logger.

    Then create a Structural Search & Replace pattern to insert the new logger declaration in the class. Search for classes without a logger declaration and use the Scope "Previous Search Results". This should insert the new logger in all classes without logger in the files found in the previous search.

    <replaceConfiguration name="Unnamed" text="class $A$ {&#10;  Logger $logger$ = Logger.GetInstance(SomeClass.class);&#10;}" recursive="false" caseInsensitive="false" type="JAVA" pattern_context="default" reformatAccordingToStyle="false" shortenFQN="false" replacement="class $A$ {&#10;  Logger logger = Logger.GetInstance(SomeClass.class);&#10;}">
      <constraint name="__context__" within="" contains="" />
      <constraint name="A" within="" contains="" />
      <constraint name="logger" minCount="0" maxCount="0" within="" contains="" />
    </replaceConfiguration>
    

    (Use the "Import Template from Clipboard" action under the tools button in the top right of the dialog)