/java:openrewritefrom java
Provides best practices for authoring OpenRewrite recipes, including MethodMatcher patterns, TypeUtils usage, and ListUtils for statement transformations.
Ships in java. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
// BAD: separate matcher per variant
private static final MethodMatcher IS_TRACE_ENABLED = new MethodMatcher("org.slf4j.Logger isTraceEnabled()");
private static final MethodMatcher IS_DEBUG_ENABLED = new MethodMatcher("org.slf4j.Logger isDebugEnabled()");
// ... repeated for info, warn, error, plus marker overloads = 10 matchers
// GOOD: single wildcard matcher
private static final MethodMatcher IS_X_ENABLED = new MethodMatcher("org.slf4j.Logger is*Enabled(..)");
This also simplifies Preconditions.check():
// BAD
Preconditions.check(or(
new UsesMethod<>(IS_TRACE_ENABLED),
new UsesMethod<>(IS_DEBUG_ENABLED),
// ... 8 more
), visitor);
// GOOD
Preconditions.check(new UsesMethod<>(IS_X_ENABLED), visitor);
Instead of manually checking method name and receiver type:
// BAD
if (!"getMessage".equals(method.getSimpleName())) return false;
Expression select = method.getSelect();
if (select == null) return false;
return TypeUtils.isAssignableTo("java.lang.Throwable", select.getType());
// GOOD
private static final MethodMatcher GET_MESSAGE = new MethodMatcher("java.lang.Throwable getMessage()");
// then: GET_MESSAGE.matches(argument)
isOfClassType() instead of manual FQN comparison// BAD
JavaType.FullyQualified type = TypeUtils.asFullyQualified(select.getType());
return type != null && "org.slf4j.Logger".equals(type.getFullyQualifiedName());
// GOOD
TypeUtils.isOfClassType(select.getType(), "org.slf4j.Logger")
TypeUtils.isOfType() instead of FQN string equality// BAD
currentType.getFullyQualifiedName().equals(targetType.getFullyQualifiedName())
// GOOD
TypeUtils.isOfType(currentType, targetType)
isAssignableTo()When matching a member's declaring type against the current class, check both exact match and subtype. Otherwise inherited members get attributed to the superclass:
// BAD: misses inherited members
if (TypeUtils.isOfType(currentType, declaringType)) { ... }
// GOOD: handles both direct and inherited members
if (TypeUtils.isOfType(currentType, declaringType) ||
TypeUtils.isAssignableTo(declaringType.getFullyQualifiedName(), currentType)) { ... }
Use the FQN-based isAssignableTo overload to handle parameterized types correctly.
instanceof JavaType.FullyQualified not JavaType.ClassJavaType.Class extends JavaType.FullyQualified, so instanceof JavaType.Class is too narrow for checks like fieldType.getOwner().
ListUtils.flatMap() instead of manual ArrayList + modified flag// BAD
List<Statement> newStatements = new ArrayList<>();
boolean modified = false;
for (Statement stmt : visited.getStatements()) {
if (shouldTransform(stmt)) {
newStatements.addAll(extractStatements(stmt));
modified = true;
} else {
newStatements.add(stmt);
}
}
if (modified) return visited.withStatements(newStatements);
return visited;
// GOOD
return visited.withStatements(ListUtils.flatMap(visited.getStatements(), stmt -> {
if (shouldTransform(stmt)) {
return extractStatements(stmt); // return List = replace with multiple
}
return stmt; // return single item = keep as-is
}));
ListUtils.map() and ListUtils.mapFirst() for whitespace adjustmentsList<Statement> bodyStatements = ListUtils.map(
extractStatements(ifStmt.getThenPart()),
st -> st.withPrefix(Space.build(whitespace, emptyList())));
return ListUtils.mapFirst(bodyStatements,
first -> first.withPrefix(ifStmt.getPrefix()));
In a composition (e.g., Slf4jBestPractices), earlier recipes transform the code before later ones see it. Don't handle cases an earlier recipe already covers.
Example: RemoveUnnecessaryLogLevelGuards should not treat string concatenation ("Name: " + name) as safe to unguard. The ParameterizedLogging recipe runs first and converts concatenation to parameterized form. If concatenation still exists when the guard-removal recipe runs, the guard is still needed for performance.
JavaElementFactory for common nodes// BAD: verbose manual construction
new J.Identifier(Tree.randomId(), Space.EMPTY, Markers.EMPTY, emptyList(), "this", ownerType, null)
// GOOD: factory method
JavaElementFactory.newThis(ownerType)
Flag enum and modifier helpers instead of magic bitmasks// BAD: magic number
(fieldType.getFlagsBitMap() & 0x0008L) != 0
// GOOD: readable API
fieldType.hasFlags(Flag.Static)
method.hasModifier(J.Modifier.Type.Static)
Java-specific recipes also run on Kotlin files unless excluded:
@Override
public TreeVisitor<?, ExecutionContext> getVisitor() {
return Preconditions.check(
Preconditions.not(new KotlinFileChecker<>()),
new MyJavaVisitor()
);
}
JavaTemplate template = JavaTemplate.builder("#{any()}.toArray(new #{}[0])")
.imports(fqn)
.build();
A template that introduces library types also needs a parser classpath:
JavaTemplate template = JavaTemplate
.builder("Your.template.code()")
.imports(
"org.assertj.core.api.Assertions",
"org.eclipse.collections.impl.utility.Iterate"
)
.javaParser(JavaParser.fromJavaVersion()
.classpath("assertj-core", "eclipse-collections", "eclipse-collections-api")
)
.build();
.contextSensitive() only when the snippet needs its surroundingsUse it when the template refers to local variables, fields, or methods of the enclosing class. A self-contained snippet such as @BeforeAll static void setUp() {} should stay context-free: context-free templates are faster and can be cached.
maybeAddImport() after applying a templateExpression result = template.apply(...);
maybeAddImport(fqn);
Call maybeRemoveImport() for types the template no longer uses.
Use JavaIsoVisitor when returning the same LST element type you visit. Use JavaVisitor when returning a different type, such as unwrapping J.Parentheses into its inner expression.
When an expression might be parenthesized, visit J.Parentheses nodes too. To replace the inner expression while keeping the parentheses and prefix, use visitedParentheses.withTree(result).
reduce for searches inside a treeTo ask "does this subtree contain X", pass the accumulator as the visitor's parameter and call reduce, rather than capturing a holder and calling visitNonNull followed by .get():
// BAD
AtomicBoolean found = new AtomicBoolean();
new JavaIsoVisitor<Integer>() { /* sets found */ }.visitNonNull(tree, 0, new Cursor(getCursor(), tree));
return found.get();
// GOOD
return new JavaIsoVisitor<AtomicBoolean>() {
@Override
public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, AtomicBoolean found) {
if (MATCHER.matches(method)) {
found.set(true);
}
return super.visitMethodInvocation(method, found);
}
}.reduce(tree, new AtomicBoolean()).get();
Pass a cursor (reduce(tree, acc, cursor)) only when the inner visitor reads getCursor(). Don't build Cursor chains by hand for visitors that never read them.
To exclude whole source files, wrap the edit visitor in a precondition instead of having the scanner record ids of files to skip:
// BAD: scanner collects UUIDs into skippedCompilationUnits; the visitor checks the set
// GOOD
return Preconditions.check(Preconditions.not(new DeclaresMethod<>(RUN_MATCHER)), new EditVisitor());
Keep a comment explaining why those files are excluded.
Prefer keying the accumulator globally (for example by fully qualified name) and treating anything ambiguous, such as a name declared in more than one module, as "don't change". Skipping a rare case is cheaper than per-project ownership logic that maintainers must reason through.
getVisitorDerive sets from the accumulator once, not inside the per-file visitor. A loop over accumulator entries per compilation unit, especially one that also walks every project, costs files × entries × projects and gets slow on large multi-module repositories.
The scanner's idea of what will change must match what the edit visitor actually reaches. If the scanner marks a declaration removable but the edit visitor never descends into its enclosing class, callers get rewritten against a declaration that still exists unchanged.
When a case can't be migrated safely, leave it unchanged and add a SearchResult marker explaining why. A visible marker beats a silently wrong rewrite.
Check what a partial migration leaves behind. Code that used to fail to compile but now compiles and fails at run time (for example a test class JUnit can no longer instantiate) is harder to spot in a large migration. Either finish the change or leave something both callers and the framework can use.
@Override
public Set<String> getTags() {
return Collections.singleton("RSPEC-S3020");
}
@Override
public Duration getEstimatedEffortPerOccurrence() {
return Duration.ofMinutes(2);
}
recipeList:
- org.openrewrite.staticanalysis.CollectionToArrayShouldHaveProperType
Common collections:
common-static-analysis.yml - General static analysis fixesjava-best-practices.yml - Java-specific best practicesstatic-analysis.yml - Broader static analysis recipesBefore submitting, run recipes at scale against large codebases (e.g., the Spring or Netflix orgs). This catches bugs unit tests miss:
SuperClass.this.method() instead of this.method())java.util.List not java.util.*)Collections.emptyList() and singletonList()@Nullable from org.jspecify.annotations on methods that can return null@NonNull on parameters (non-null is the default)Recipe tests often fail on import order alone, not on the transformation:
-import java.util.List;
-import org.assertj.core.api.Assertions;
+import org.assertj.core.api.Assertions;
+import java.util.List;
If imports are missing entirely, fix the recipe: declare them on the JavaTemplate and call maybeAddImport / maybeRemoveImport, as described under JavaTemplate Usage above.
If only the order differs, accept the order OpenRewrite produces rather than forcing your own: copy the actual output from the failure into the expected text, confirm the transformation itself is right, and rerun. OpenRewrite typically orders imports as third-party packages, blank line, java.* / javax.*, then static imports after another blank line.
"""
import org.assertj.core.api.Assertions;
import org.eclipse.collections.impl.utility.Iterate;
import java.util.List;
"""
The ~~> prefix ("ignore everything before this line") is not recognized in every codebase. If it fails, remove it and match exactly.
For tests with custom types that lack complete type information, prefer types that exist on the classpath. Disable validation only as a last resort:
rewriteRun(
spec -> spec.typeValidationOptions(TypeValidation.none()),
java(...)
);
Test inputs contain intentional issues. Suppress the resulting IDE warnings with @SuppressWarnings on the test method, or on the class when several tests share it. Common values: "RedundantCast", "ConstantConditions", "unused", "unchecked".
Add //language=java for IDE highlighting. With a plain java("before", "after") call, put it before java. With a spec customization or several java() calls, put it on the individual strings.
Do not add //language=java to JavaTemplate strings containing #{any()} or #{}; they are not valid Java.
Write one test method per scenario, not one test with dozens of sources or a parameterized test over several fixtures. Each test then has one reason to pass, a failure points at the case that broke, and no source passes for the wrong reason. Group related scenarios in a @Nested class, and tag a reproducer from an issue with @Issue.
Place new tests after the @DocumentExample test.
Avoid withMaxCycles(1) to make a test pass. Make the visitor stop once its change is done (for example by matching its own output) and let the default cycles run, which also exercises the second cycle, where markers added in the first are already present.
When a change affects type attribution, assert the resulting types in afterRecipe, for example by collecting getMethodType() and argument types with a visitor's reduce and comparing them with containsExactly.
Cover basic cases, edge cases (custom types, fully qualified types), cases where the recipe must not change anything, import handling, and formatting preservation. Cover every branch of new code, including fallbacks.
Probe the shapes that commonly break recipes:
new Foo(x) {} carries the anonymous class's constructor type, not Foo'ssuper() once a base constructor loses its argumentsWhen a PR also fixes something on the side, such as a guard that stops the recipe from damaging Kotlin files, mention it in the description so it shows up in the release notes.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub motlin/claude-code-plugins --plugin java6 skills in this plugin
/liquibase-lock-resolverDiagnose Liquibase change-log lock failures in Maven tests and remove only stale H2 database files from build output directories before rerunning the affected tests. Use when failures contain "Could not acquire change log lock", "Currently locked by", or `liquibase.exception.LockException`./maven-cliMaven CLI invocation patterns. Use whenever running `mvn` commands in Java/Maven projects. Covers when `-am` is required, why `-o` (offline) mode hides bugs in multi-worktree setups, and how to verify compile/test cleanly without trusting stale `~/.m2` artifacts./openrewrite-analyze-recipesDry-run configured OpenRewrite recipes, count and rank violations per recipe, and optionally run one selected recipe without committing. Use when asked to analyze OpenRewrite recipes, report rule violations, inspect a rewrite dry run, or compare which recipes would change the most files.Other plugins' skills for the same job