Custom Slash Commands in Claude Code for Java Workflows

  • Last Updated: May 8, 2026
  • By: javahandson
  • Series
img

Custom Slash Commands in Claude Code for Java Workflows

Learn how to create custom slash commands in Claude Code for Java workflows like source code generation, test generation, code review, security reviews, and documentation, etc.

One of the least talked-about but most practically useful features of Claude Code is the ability to define your own custom slash commands. These are reusable, named prompts that you trigger in any Claude Code session with a single /command invocation. For Java developers who find themselves repeatedly describing the same types of tasks — write tests for this class, review this method for code smells, add logging to this service, generate API documentation — custom commands turn those repetitive instructions into one-word shortcuts.

The idea is simple, but the impact is significant. Instead of carefully typing out a multi-line instruction each time you want Claude Code to perform a standard task, you define the instruction once in a Markdown file, give it a name, and invoke it with a /slash. Claude Code reads the command definition, substitutes any arguments you provide, and executes the full instruction. Your most carefully crafted prompts become permanently available, session after session, across all your projects.

This matters especially because Claude Code’s output quality depends heavily on the prompt. When you type a quick instruction on the spot, it may be vague, lack context, or fail to specify the exact pattern you want. When you write a command definition carefully — once — and refine it based on observed output, every future invocation gets the benefit of that work. Custom commands are how you turn prompt engineering insights into permanent workflow improvements.

This article covers everything you need to know about custom slash commands in Claude Code: how they work structurally, where to store them for global or project-scoped access, how to write effective command prompts specifically for Java workflows, and a complete library of twelve practical commands you can adopt or adapt immediately for your own projects.

1. What Are Custom Slash Commands?

In Claude Code, slash commands are shortcuts that execute a predefined prompt. Built-in commands like /help, /clear, and /compact are part of Claude Code itself. Custom slash commands are ones you define — stored as Markdown files in a directory that Claude Code reads at startup.

When you type /generate-tests CustomerService in a Claude Code session, Claude Code looks up the corresponding command file, reads the prompt template it contains, substitutes ‘CustomerService’ in place of the $ARGUMENTS placeholder, and executes the resulting full prompt — exactly as if you had typed the complete multi-line instruction manually. The difference is that the complete instruction was written once, refined over time, and is now available instantly from a two-word invocation.

This matters because the quality of the output from a carefully crafted full prompt is substantially better than the output from a brief, improvised instruction. The brief instruction ‘write tests for CustomerService’ will produce tests. The full prompt that specifies the test framework, assertion library, method naming convention, coverage requirements, and post-generation verification step will produce tests that fit your project and pass your CI checks on the first attempt. Custom commands make the full-quality prompt the default, not the exception.

2. Where to Store Custom Commands

Claude Code looks for custom commands in two locations. The choice between them determines whether a command is available globally across all your projects or only locally within a specific project.

Global commands are stored in ~/.claude/commands/ inside your home directory. Any .md file you place here is available in every Claude Code session on your machine, regardless of which project you are in. This is the right location for commands that are useful across all Java projects — general unit test generation, code review checklists, JavaDoc generation, and Java version migration. These commands are yours, personal to your machine and workflow.

Project-level commands are stored in .claude/commands/ at the root of a specific project. Commands here are only available when you are running Claude Code inside that project directory. This is the right location for commands specific to a particular project — full CRUD endpoint scaffolding that follows your exact entity structure, project-specific quality checks, or workflow automation that references your module layout. Project-level commands should be committed to version control. When your team members clone the repository, they automatically receive the commands and benefit from the same workflow tooling.

# Global commands — available in every Claude Code session:
~/.claude/commands/
  generate-tests.md
  review-code.md
  add-javadoc.md
  add-logging.md
  check-security.md
  migrate-java.md
  explain-code.md
 
# Project-level commands — available only in this project, committed to git:
/your-project/.claude/commands/
  new-endpoint.md        # Creates complete CRUD stack following project conventions
  prep-pr.md             # Full pre-PR build, test, review, and commit message
  find-tests.md          # Audits project for missing test coverage
  run-quality-check.md   # Project-specific quality gates

3. Anatomy of a Custom Command File

Each custom command is a Markdown file whose name (without the extension) becomes the slash command name. A file named generate-tests.md creates the /generate-tests command. The file’s contents are the prompt that runs when the command is invoked.

The most important placeholder variable is $ARGUMENTS. This captures everything you type after the command name when you invoke it. If you run /generate-tests CustomerService, then $ARGUMENTS is substituted with ‘CustomerService’ everywhere it appears in the prompt. Commands without $ARGUMENTS are also valid — they execute the same full prompt every time with no variable input.

# Example command file: ~/.claude/commands/generate-tests.md
 
Generate comprehensive unit tests for the Java class: $ARGUMENTS
 
Requirements:
1. Use JUnit 5 with @ExtendWith(MockitoExtension.class)
2. Use AssertJ for all assertions — never org.junit.jupiter.api.Assertions
3. Name test methods: methodName_condition_expectedBehaviour
4. Mock all dependencies with @Mock, inject with @InjectMocks
5. Cover: happy path, boundary conditions, and all exception paths
6. Place the test class in the matching package under src/test/java/
7. Follow the test structure shown in CLAUDE.md testing standards
 
After writing the test file, run: mvn test -pl .
Fix any compilation errors or test failures before reporting back.

When you invoke /generate-tests OrderService, Claude Code reads this file, replaces $ARGUMENTS with ‘OrderService’, and executes the full prompt. It then finds OrderService.java, analyses every public method, generates a complete OrderServiceTest.java in the correct package, writes the file, runs the test command, reads the results, and fixes any issues — all from a single two-word command. This is the power of packaging a well-crafted prompt into a command.

4. A Complete Java Command Library

Here is a set of twelve custom commands designed specifically for Java developers. Each addresses a genuine workflow need, is written to produce high-quality, consistent output, and can be adopted directly or used as a starting point for your own variations.

4.1 /generate-tests — Unit Test Generator

# ~/.claude/commands/generate-tests.md
 
Generate comprehensive JUnit 5 unit tests for: $ARGUMENTS
 
Requirements:
- @ExtendWith(MockitoExtension.class) on the test class
- @Mock for all dependencies, @InjectMocks for the class under test
- AssertJ assertions only (never org.junit.jupiter.api.Assertions)
- Test naming: methodName_condition_expectedResult
- Cover: happy path, all conditional branches, and exception scenarios
- For void methods: verify interactions using Mockito verify()
- Place output in the matching package under src/test/java/
 
After writing the test file, run the tests and fix any failures.

4.2 /review-code — Structured Code Review

# ~/.claude/commands/review-code.md
 
Perform a structured code review of: $ARGUMENTS
 
Review the following categories:
 
Correctness:
- Null pointer risks and missing null checks
- Incorrect exception handling or swallowed exceptions
- Missing edge case handling
- Thread safety issues
 
Design:
- Single Responsibility Principle violations
- Unnecessary coupling between classes
- Missing abstractions or overly exposed internals
 
Java Best Practices:
- Resource management (try-with-resources for closeable resources)
- Raw types or unchecked warnings
- Unnecessary mutability
- Appropriate use of Java 21 features
 
Spring-Specific:
- N+1 query risks in JPA relationships
- Transactional boundary correctness
- Missing or incorrect exception handling in REST controllers
 
Report issues with priority:
  CRITICAL — blocks merge
  IMPORTANT — should fix soon
  MINOR — consider improving
 
For each issue: exact location, explanation, and suggested fix.

4.3 /add-javadoc — JavaDoc Generator

# ~/.claude/commands/add-javadoc.md
 
Add comprehensive JavaDoc to all public methods in: $ARGUMENTS
 
For each public method generate:
- One-sentence description: what it does (not how)
- @param for each parameter: type, purpose, valid range if applicable
- @return description: what is returned and when
- @throws for all checked exceptions and documented unchecked exceptions
 
Style rules:
- Third person imperative: 'Returns the customer...' not 'This returns...'
- Be concise: prefer one clear sentence over three vague ones
- Do NOT add JavaDoc to private methods or trivial getters/setters
- Do NOT add JavaDoc to @Override methods where parent doc suffices
 
After adding JavaDoc, run mvn compile to verify no syntax errors.

4.4 /add-logging — SLF4J Logging

# ~/.claude/commands/add-logging.md
 
Add SLF4J logging to the Java class: $ARGUMENTS
 
Logging requirements:
- Add @Slf4j (Lombok) if Lombok is available, else private static Logger
- INFO: method entry for public methods (key parameters only — no PII)
- INFO: successful completion of meaningful business operations
- DEBUG: internal state and intermediate processing results
- WARN: recoverable unexpected states
- ERROR: all caught exceptions with log.error(message, exception)
 
Security requirements:
- Never log passwords, API keys, tokens, or secrets
- Never log full request/response bodies
- Mask or omit PII (email, phone, national ID)
- Include correlation IDs from MDC if available: MDC.get("traceId")
 
After adding logging, run mvn compile to verify.

4.5 /new-endpoint — Full CRUD Endpoint Scaffold

# .claude/commands/new-endpoint.md  (project-level)
 
Scaffold a complete REST CRUD endpoint for the entity: $ARGUMENTS
 
Generate all of the following, following every convention in CLAUDE.md:
 
1. JPA Entity class
   @Entity, @Table, @Id with @GeneratedValue(IDENTITY)
   @CreatedDate, @LastModifiedDate (via @EnableJpaAuditing)
 
2. JPA Repository interface
   Extend JpaRepository<[Entity], Long>
   Add findByXxx methods for obvious business queries
 
3. Service class
   Constructor injection of repository
   findById — throws ResourceNotFoundException if absent
   findAll — returns Page<[Entity]Response> with pagination
   create, update, delete methods
 
4. REST Controller
   GET    /api/v1/[entities]        — paginated findAll
   GET    /api/v1/[entities]/{id}   — findById
   POST   /api/v1/[entities]        — create (body: Create[Entity]Request)
   PUT    /api/v1/[entities]/{id}   — update (body: Update[Entity]Request)
   DELETE /api/v1/[entities]/{id}   — delete
   Use ResponseEntity<T> for all methods. @Valid on request bodies.
 
5. DTOs (Java records)
   Create[Entity]Request  — with Bean Validation annotations
   Update[Entity]Request  — all fields optional for partial update
   [Entity]Response       — safe for API exposure (no sensitive fields)
 
6. Unit tests for the service class
 
After creating all files, run mvn compile to verify. Fix any errors.

4.6 /check-security — Security Review

# ~/.claude/commands/check-security.md
 
Perform a security review of: $ARGUMENTS
 
Check for:
 
Input Validation:
- Missing @Valid on @RequestBody parameters
- No size limits on String inputs (@Size, @Length)
- SQL injection risk in native queries or JPQL with string concatenation
- Missing range validation on numeric inputs
 
Authorisation:
- Endpoints missing @PreAuthorize or security configuration coverage
- Insecure Direct Object Reference: accessing /api/items/{id} without
  verifying the caller owns that item
- Privilege escalation risks in role checks
 
Data Exposure:
- JPA entities returned directly from controllers (bypass DTO layer)
- Sensitive fields (password hash, token) in response DTOs
- Excessive data in list endpoints (no pagination, no field filtering)
 
Error Handling:
- Stack traces or exception messages exposed in API error responses
- Internal class names or file paths revealed in errors
 
Report severity: CRITICAL / HIGH / MEDIUM / LOW with remediation steps.

4.7 /explain-code — Code Explainer

# ~/.claude/commands/explain-code.md
 
Explain the following Java code clearly and thoroughly: $ARGUMENTS
 
Structure the explanation as:
 
Purpose: What this code does and why it exists in the system
 
Design: Key design decisions, patterns used, and why they were chosen
 
Flow: Step-by-step walkthrough of the main execution path
 
Dependencies: External systems, services, or components this relies on
 
Edge Cases: Important boundary conditions and how they are handled
 
Potential Issues: Anything fragile, unclear, or worth flagging for review
 
Pitch the explanation at a mid-level Java developer who knows Spring Boot
but is not familiar with this specific module.

4.8 /migrate-java — Java 21 Migration

# ~/.claude/commands/migrate-java.md
 
Migrate the following Java file to idiomatic Java 21: $ARGUMENTS
 
Apply these modernisations where appropriate:
- Simple data holders → Java records
- instanceof + cast → pattern matching instanceof
- Multi-line strings → text blocks
- Traditional switch statements → switch expressions
- Null checks → Optional where it improves clarity
- Local variable types → var where obvious
- Anonymous Runnable → lambdas/method references
 
For each change applied:
- Show before and after
- Explain the improvement
- FLAG: any change that could alter runtime behaviour
  (these require your explicit review before accepting)
 
After applying all changes, run mvn test to verify nothing broke.

4.9 /find-tests — Coverage Audit

# .claude/commands/find-tests.md  (project-level)
 
Audit this project for missing test coverage.
 
Instructions:
1. Find all classes ending with Service or Controller in src/main/java/
2. For each, check if a corresponding test class exists in src/test/java/
3. For existing test classes, count public methods vs @Test methods
 
Report:
 
TEST COVERAGE AUDIT
 
No test file at all:
  [List of untested classes — full qualified name]
 
Test file exists but likely incomplete:
  [ClassName]: X public methods, Y @Test methods
 
Well covered (>=80% method coverage estimate):
  [ClassName]: X public methods, Y @Test methods
 
Total: [N] classes audited, [M] fully untested, [P] partially tested

4.10 /write-changelog — Changelog Entry

# ~/.claude/commands/write-changelog.md
 
Analyse recent git history and write a changelog entry.
 
Steps:
1. Run: git log --oneline -20
2. Group commits by type: Features, Bug Fixes, Breaking Changes, Dependencies
3. Write user-facing descriptions (not raw commit messages)
4. Use Keep a Changelog format (https://keepachangelog.com)
 
Version header: $ARGUMENTS
If no argument provided, use [Unreleased] as the header.
 
Example output format:
## [1.5.0] - 2026-05-01
### Added
- Customer search by email with partial matching
### Fixed
- Pagination now returns correct total count for filtered results

4.11 /add-integration-test — Integration Test Generator

# ~/.claude/commands/add-integration-test.md
 
Create a @DataJpaTest integration test for the repository: $ARGUMENTS
 
Requirements:
- @DataJpaTest (uses in-memory H2 by default)
- @AutoConfigureTestDatabase(replace = NONE) if Testcontainers is available
- Test data setup using @BeforeEach or test-specific helper methods
- Test all custom query methods in the repository interface
- Verify: happy path queries, empty results, and ordering/pagination
 
If Testcontainers is in pom.xml:
  Use @Testcontainers with @Container PostgreSQLContainer for real DB
 
After creating the test, run: mvn test -pl . -Dtest=[TestClassName]
Fix any failures before reporting back.

4.12 /prep-pr — Pre-PR Workflow Automation

# .claude/commands/prep-pr.md  (project-level)
 
Prepare the current changes for a pull request review.
 
Execute these steps in order, stopping and reporting if any step fails:
 
Step 1 — Build verification
Run: mvn clean install
If build fails: stop, report the error, do not continue.
 
Step 2 — Full test suite
Run: mvn test
Report any failures. Attempt to fix obvious test failures.
If more than 5 tests fail: stop and report — likely a systemic issue.
 
Step 3 — Checkstyle
Run: mvn checkstyle:check
Fix any checkstyle violations.
 
Step 4 — Self code review
For each file in: git diff --name-only HEAD
  - Check for debug code or temporary comments
  - Check for missing error handling
  - Check that new public methods have JavaDoc
  - Check for obvious security issues
 
Step 5 — Commit message
Run: git diff --stat HEAD
Write a conventional commit message:
  type(scope): brief description under 72 chars
 
  Body: what changed and why (wrap at 72 chars)
  Closes: #[issue-number if applicable]
 
Step 6 — PR description
Generate a PR description template:
  ## What
  ## Why
  ## Testing
  ## Reviewer Notes

5. Writing Effective Command Prompts

The quality of a custom command depends entirely on the quality of the prompt inside it. Several principles consistently separate commands that produce excellent results from those that produce mediocre ones.

The first principle is the specificity of output format. Tell Claude Code exactly what output you want. If you want a Java file created at a specific path, say so. If you want a numbered list of issues, specify that. If you want the command to run a verification step after making changes, include it explicitly. Claude Code reliably follows specific output format instructions; it guesses at vague ones.

The second principle is the verification step. The best commands end by running a verification — typically mvn test or mvn compile. This catches errors before Claude Code declares the task complete, and means you do not need to remember to run the build yourself. A command that creates files and then verifies they compile is dramatically more valuable than one that creates files and stops.

The third principle is the right level of constraint. Commands that are too specific can produce rigid output that does not adapt well to different situations. Commands that are too open-ended produce inconsistent results. The right balance is to specify what and the expected output format, while leaving Claude Code to figure out the exact implementation details based on the current file’s context and the project’s CLAUDE.md.

The fourth principle is testing and iteration. Write a command, use it on three or four different classes, observe where the output deviates from your expectations, and refine the prompt to address those deviations. A command you have tested and refined on real examples will consistently outperform one written once and never revisited.

Interview Insight: Being able to describe custom slash commands you have built — the specific prompts you wrote, the iteration process you went through to refine them, how you share them with your team via version control — demonstrates a sophisticated, production-oriented approach to AI-assisted development. It shows that you are actively engineering your workflow, not just using AI tools passively as they come out of the box.

6. Sharing Commands Across Your Team

Project-level commands stored in .claude/commands/ and committed to version control are automatically available to every team member who clones the repository. This is one of the most valuable aspects of the project-level command location and a strong argument for investing time in well-crafted project commands.

When a senior developer invests three hours in writing and refining a /new-endpoint command that produces production-ready Spring Boot CRUD stacks that follow the project’s exact conventions, every developer on the team immediately benefits from that investment. The junior developer who uses /new-endpoint receives the same quality of output as the senior developer. The code review conversation shifts from ‘you used the wrong test pattern’ to ‘let us discuss the business logic’ — which is a much more productive use of review time.

For teams adopting Claude Code, starting with a shared set of three to five high-quality project commands is more effective than letting everyone build their own personal commands in isolation. The shared commands establish a consistent baseline quality for AI-generated code across the team and clearly demonstrate the tool’s value from the first week of adoption.

7. The Synergy Between Commands and CLAUDE.md

Custom commands and CLAUDE.md are designed to work together, and their combination is more powerful than either in isolation. CLAUDE.md provides the persistent project context — architecture, conventions, constraints — that applies to every session. Custom commands provide the task-specific instructions — what to do and exactly how to do it for this type of operation.

When you invoke /generate-tests CustomerService, Claude Code has both the command instructions (JUnit 5, AssertJ, specific naming convention, run tests after) and the CLAUDE.md context (project package structure, where test files go, which test patterns exist, which build command to use). The combination produces output that is both technically correct and fits the specific project. Neither alone achieves the same result.

Commands can also explicitly defer to CLAUDE.md for certain details. You can write a command that includes ‘follow the testing standards documented in CLAUDE.md’ as part of its instructions. This keeps the command concise while ensuring that project-specific conventions are respected. When conventions evolve, and CLAUDE.md is updated, the command automatically benefits from the update without needing to be rewritten.

8. Organising and Documenting Your Command Library

As your command library grows, organisation and documentation become important. A few simple practices keep things manageable and ensure your commands are discoverable and used.

Use a consistent naming convention. The verb-noun pattern works well: generate-tests, add-logging, review-code, check-security, and find-tests. This makes commands easy to remember and easy to guess. A developer who has used /generate-tests can reasonably guess that /generate-integration-tests might exist.

Document your available commands in your project’s README or in a section of CLAUDE.md. A simple table with command names and one-line descriptions is enough. When new developers join the project and see that /new-endpoint creates a complete CRUD stack in one command, adoption of Claude Code accelerates immediately.

## Claude Code Custom Commands (add to project README)
 
Project-level commands available in Claude Code:
 
| Command                     | What it does                                     |
|-----------------------------|--------------------------------------------------|
| /new-endpoint [Entity]      | Scaffolds complete CRUD stack (entity to test)   |
| /find-tests                 | Audits project for missing test coverage         |
| /prep-pr                    | Full pre-PR build, review, and message gen       |
| /run-quality-check          | Runs all project quality gates                   |

9. Conclusion

Custom slash commands transform Claude Code from a capable conversational tool into a personalized development-automation platform. By investing time up front in writing high-quality command definitions, you create a library of reusable, refined instructions that encode your team’s best practices and produce consistent results, session after session.

For Java developers, the commands that deliver the most immediate practical value are unit test generation, structured code review, full CRUD endpoint scaffolding, and pre-PR workflow automation. Start with those four. Use them for real work. Refine them based on what you observe. Add new commands as you identify other recurring tasks that would benefit from standardised automation.

The combination of a well-maintained CLAUDE.md and a thoughtful library of custom commands creates a development environment in which the mechanical, repetitive aspects of Java development are handled reliably by Claude Code, while your attention stays on the architectural decisions, business logic, and problem-solving that genuinely require human expertise. That is the developer workflow that custom commands are designed to enable.

Leave a Comment