HOOK · deterministic-policy

PostToolUse hook: format Java on edit

Runs Spotless on any Java file Claude Code edits, so formatting is never a review comment.

✓ verified 2026-06-10 · stack: java, claude-code, spotless · source

Add to .claude/settings.json:

.claude/settings.json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "jq -r '.tool_input.file_path' | { read f; case \"$f\" in *.java) ./gradlew spotlessApply -PspotlessIdeHook=\"$f\" --quiet ;; esac; }"
}
]
}
]
}
}

What it does

PostToolUse fires after every Edit or Write tool call. The command reads the tool-call JSON from stdin, extracts .tool_input.file_path with jq, and passes the path to Spotless via the Gradle IDE hook (-PspotlessIdeHook). The case statement means only .java files are touched; all other extensions fall through silently.

The Gradle IDE hook instructs spotlessApply to format that single file rather than the whole project, so the cost is proportional to one file. Formatting becomes a property of the system, not a request to the model.

Hooks run with the working directory set to wherever Claude Code was started. If your ./gradlew wrapper is not at that root, pin the path with ${CLAUDE_PROJECT_DIR}: for example, "${CLAUDE_PROJECT_DIR}"/gradlew spotlessApply ....

Failure modes

  • jq absent. The command errors and exits non-zero (but not 2), which Claude Code treats as non-blocking: the edit proceeds unformatted. Mitigate with a preflight check in CI or a SessionStart hook that asserts command -v jq.
  • Spotless plugin version lacking spotlessIdeHook. The flag was introduced in Spotless Gradle plugin 5.x. On an older version Gradle will either fail with an unknown property error or scan the whole project, costing project-proportional time. Pin and verify the plugin version before deploying.
  • Wrong CWD or ./gradlew not found. Gradle exits non-zero; the error is non-blocking, so the edit proceeds but is not formatted. If your session CWD is not the project root, use ${CLAUDE_PROJECT_DIR} to anchor the gradlew call.
  • Non-Java files. The case statement passes them through untouched by design. The hook never invokes Gradle on TypeScript, YAML, or any other extension.

Verified 2026-06-10 against the hooks guide auto-format example at https://code.claude.com/docs/en/hooks-guide and the Spotless Gradle IDE hook doc.