IntelliJ Structural Replacement Templates | Generated by AI
Here are 10 examples of IntelliJ’s Structural Replacement templates, categorized for clarity. These can be incredibly powerful for refactoring, enforcing coding standards, and automating common code transformations.
Basic Refactoring & Simplification:
-
Replace
if (condition) return true; else return false;
withreturn condition;
- Search Template:
if ($CONDITION$) { return true; } else { return false; }
- Replacement Template:
return $CONDITION$;
- Context: Simplifies boolean return statements.
- Search Template:
-
Replace
if (condition) { statement; }
withif (!condition) { continue/break/return; }
(Guard Clause)- Search Template:
if ($CONDITION$) { $STATEMENTS$; }
- Replacement Template: (This one is more about suggesting a transformation, you’d manually adjust the inner part)
if (!$CONDITION$) { // Consider continue, break, or return here } $STATEMENTS$;
- Context: Encourages the use of guard clauses for cleaner code flow. You’d typically use a “Replace with” action after finding the structure.
- Search Template:
Collection & Stream Operations:
-
Replace
for (Type item : collection) { if (item.getProperty() == value) { ... } }
with Streamfilter
- Search Template:
for ($TYPE$ $ITEM$ : $COLLECTION$) { if ($ITEM$.$METHOD$($VALUE$)) { $STATEMENTS$; } }
- Replacement Template:
$COLLECTION$.stream() .filter($ITEM$ -> $ITEM$.$METHOD$($VALUE$)) .forEach($ITEM$ -> $STATEMENTS$); // Or .map().collect(), etc.
- Context: Migrating from traditional loops to Java Streams for filtering. This is a general example; you’d likely need more specific templates for
map
,collect
, etc.
- Search Template:
-
Replace
new ArrayList<>().add(item1); new ArrayList<>().add(item2);
withList.of(item1, item2);
- Search Template: (This might require multiple templates for varying numbers of
add
calls, or a more complex regex foradd
calls. A simpler approach for 2 items):java.util.ArrayList<$TYPE$> $LIST$ = new java.util.ArrayList<>(); $LIST$.add($ITEM1$); $LIST$.add($ITEM2$);
- Replacement Template:
java.util.List<$TYPE$> $LIST$ = java.util.List.of($ITEM1$, $ITEM2$);
- Context: Using Java 9+
List.of()
for immutable lists.
- Search Template: (This might require multiple templates for varying numbers of
Error Handling & Resource Management:
-
Replace
try { ... } catch (Exception e) { e.printStackTrace(); }
with more specific logging- Search Template:
try { $STATEMENTS$; } catch (java.lang.Exception $EXCEPTION$) { $EXCEPTION$.printStackTrace(); }
- Replacement Template:
try { $STATEMENTS$; } catch (java.lang.Exception $EXCEPTION$) { // Replace with your preferred logging framework, e.g.: // logger.error("An error occurred", $EXCEPTION$); throw new RuntimeException($EXCEPTION$); // Or rethrow a specific exception }
- Context: Encourages proper error logging instead of just printing stack traces.
- Search Template:
-
Replace
try { ... } finally { closeable.close(); }
withtry-with-resources
- Search Template:
java.io.Closeable $CLOSEABLE$ = null; try { $CLOSEABLE$ = $INITIALIZATION$; $STATEMENTS$; } finally { if ($CLOSEABLE$ != null) { $CLOSEABLE$.close(); } }
- Replacement Template:
try ($CLOSEABLE$ = $INITIALIZATION$) { $STATEMENTS$; }
- Context: Modernizing resource management to use
try-with-resources
(Java 7+).
- Search Template:
Class & Method Structure:
-
Find fields that can be
final
- Search Template:
class $CLASS$ { $TYPE$ $FIELD$; }
- Replacement Template: (This is more for finding, then using a quick fix)
class $CLASS$ { // Consider making this final if it's only assigned once final $TYPE$ $FIELD$; }
- Context: Identifying opportunities to improve immutability. You’d set up a filter to only show fields without multiple assignments.
- Search Template:
-
Replace
private static final Logger logger = LoggerFactory.getLogger(MyClass.class);
with a custom logger utility- Search Template:
private static final org.slf4j.Logger $LOGGER_VAR$ = org.slf4j.LoggerFactory.getLogger($CLASS_NAME$.class);
- Replacement Template:
private static final org.slf4j.Logger $LOGGER_VAR$ = com.yourcompany.util.LoggerProvider.getLogger(); // Or a more specific getLogger($CLASS_NAME$.class) from your utility
- Context: Enforcing a specific logging initialization pattern across your codebase.
- Search Template:
Annotations & Boilerplate:
-
Add
@Override
to methods overriding superclass methods (if missing)- Search Template: (This is more complex and often better handled by IntelliJ’s built-in inspections, but for demonstration)
class $CLASS$ { $RETURN_TYPE$ $METHOD$($PARAMS$) { $STATEMENTS$; } }
- Replacement Template: (Again, for finding, then applying a quick fix)
class $CLASS$ { @Override // Add if it overrides a superclass method $RETURN_TYPE$ $METHOD$($PARAMS$) { $STATEMENTS$; } }
- Context: Enforcing good practice and catching typos. You’d use a filter to check if the method exists in a superclass/interface.
- Search Template: (This is more complex and often better handled by IntelliJ’s built-in inspections, but for demonstration)
-
Replace repetitive
getter/setter
methods with Lombok annotations- Search Template: (For a single getter, this would be highly repetitive for a class)
public $TYPE$ get$PROPERTY_NAME$() { return this.$FIELD_NAME$; }
- Replacement Template: (This is conceptual, as you’d delete the getter and add
@Getter
to the field or class)// Consider replacing with @lombok.Getter on the field: // @lombok.Getter // private $TYPE$ $FIELD_NAME$;
- Context: Automating the transition to Lombok. For a full class, you might target the class itself and suggest
@Data
or@Getter/@Setter
annotations based on the presence of these methods. This is one of the more advanced and potentially multi-step transformations.
- Search Template: (For a single getter, this would be highly repetitive for a class)
How to Use Them in IntelliJ:
- Go to
Analyze
->Inspect Code...
- In the
Inspection Profile
window, click on the...
next to the profile name to edit it. - Navigate to
Java
->General
->Structural Search Inspection
. - Click the
+
button to add a new search/replace template. - Define your
Search Template
andReplacement Template
. - Use the
Variables
tab to define constraints for your variables (e.g., type, text, count). - Run the inspection on your code. IntelliJ will suggest replacements or highlight findings.
These examples demonstrate the versatility of Structural Search and Replace. The more specific and constrained your templates are, the more accurate and useful the replacements will be.