Community程式設計與開發github.com

adityamparikh/effective-modern-java

Version-calibrated Java coding skill. Reads the project's maven.compiler.release or Gradle toolchain, uses only features final in that release (17, 21, 25 LTS and the JDKs between), proves it with javac --release, and applies Effective Java (3rd ed.) as updated for modern Java — records, sealed types, pattern switch, virtual threads, scoped values. Use whenever you write, refactor, modernize, upgrade or review plain Java code — e.g. "write a Java class for…", "clean this up", "make this idiomatic", "upgrade to Java 21/25", "review this before I merge", or pasted Java asking for improvements. Not for framework-specific work (Spring wiring, JPA mappings), test-tool choice, JVM tuning, or Kotlin.

effective-modern-java 是什麼?

effective-modern-java is a Claude Code agent skill that version-calibrated Java coding skill. Reads the project's maven.compiler.release or Gradle toolchain, uses only features final in that release (17, 21, 25 LTS and the JDKs between), proves it with javac --release, and applies Effective Java (3rd ed.) as updated for modern Java — records, sealed types, pattern switch, virtual threads, scoped values. Use whenever you write, refactor, modernize, upgrade or review plain Java code — e.g. "write a Java class for…", "clean this up", "make this idiomatic", "upgrade to Java 21/25", "review this before I merge", or pasted Java asking for improvements. Not for framework-specific work (Spring wiring, JPA mappings), test-tool choice, JVM tuning, or Kotlin.

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/adityamparikh/effective-modern-java/tree/HEAD

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Effective Modern Java

Write Java that compiles on the project's JDK and that a careful reviewer would approve. You already know Java. This skill covers what models still get wrong: features newer than the project's release, modern features with non-obvious traps, Effective Java advice that newer releases changed, and "best practices" that break callers when applied to existing code.

Step 1 — Find the Java baseline before writing a line

WhereWhat to read
pom.xmlmaven.compiler.release, <release> in maven-compiler-plugin, java.version (Spring Boot parent), maven.compiler.source/target
build.gradle(.kts)options.release, java.toolchain.languageVersion, sourceCompatibility
Elsewhere.java-version, .sdkmanrc, .tool-versions, CI setup-java, Dockerfile base image

Precedence: an explicit release (maven.compiler.release, options.release) wins over the toolchain, which wins over JAVA_HOME. A Gradle toolchain of 21 with options.release = 17 means you write Java 17. Check for --enable-preview in the compiler args. If it's absent, preview features are off-limits, whatever the JDK.

  • Libraries consumed by other teams: the declared release is a promise to their JDKs, so never raise it to use a feature. For a newer fast path, use a multi-release JAR or a Runtime.version().feature() check.
  • Found → never use a feature newer than that release. If a newer feature would clearly help, write the compatible version and mention the upgrade in one sentence.
  • No project / not found → use the version the user named. Otherwise target Java 25 (the latest LTS; 26 and 27 are non-LTS) and state that assumption in one line.

Release gates (final features; this table is the source of truth):

ReleaseUsable from here on
17 (LTS)records, sealed types, instanceof patterns, switch expressions, text blocks, var, Stream.toList(), RandomGenerator, HexFormat
18UTF-8 default charset, {@snippet} Javadoc, finalization deprecated for removal
19ExecutorService is AutoCloseable; Future.state()/resultNow()
21 (LTS)pattern switch (when, case null), record patterns, virtual threads, SequencedCollection/Map (getFirst, getLast, reversed), Math.clamp, StringBuilder.repeat
22unnamed variables/patterns _, Foreign Function & Memory API
23Markdown doc comments ///
24stream gatherers (Gatherers.windowFixed/windowSliding/fold/scan/mapConcurrent); synchronized no longer pins virtual threads (JEP 491)
25 (LTS)ScopedValue, flexible constructor bodies, import module, compact source files + instance main, KDF API
26, 27no new language features; HTTP/3 in HttpClient (26)
Preview only (through 27)StructuredTaskScope (final targeted for 28), primitive patterns, StableValue/LazyConstant
NeverSTR."…" string templates (withdrawn, removed in 23)

Per-feature notes, JEPs and BAD/GOOD code: references/modern-java.md.

Step 2 — Defaults to apply without being asked

These are for new code. For existing code, Step 3's refactoring rules take precedence. Each default says why, so you can deviate when the reason doesn't apply. When you do, say so.

Types

  • Values are records. Validate in the compact constructor and copy mutable components there (items = List.copyOf(items)). Override toString when a component is secret. Not for JPA entities, mutable state, or identity types.
  • Closed alternatives → sealed interface + records. On 21+, consume them with a switch expression with no default, so adding a variant breaks the build everywhere it matters. On 17 there's no pattern switch: put an abstract method on the interface, or use a visitor, to get the same compile-time guarantee. An instanceof chain ending in throw gives no guarantee.
  • Fixed constant sets → enums with data and behavior; EnumMap/EnumSet; never compute with or persist ordinal().
  • Money → BigDecimal built from String/valueOf, with an explicit RoundingMode on every division or rate. A Money record that stores amounts at currency scale must normalize scale in its compact constructor, or the generated equals says 2.0 ≠ 2.00. Use amount.setScale(digits, RoundingMode.UNNECESSARY): it rejects 10.005 USD instead of silently rounding it. Guard Currency.getDefaultFractionDigits() < 0 (XAU, XXX). Unit prices and FX rates that need more precision belong in a separate type.
  • IDs, codes, quantities → small records or enums (OrderId, Weight), not bare String/double. Inject a Clock where tests need "now".

APIs

  • Make classes final or sealed unless designed for extension. Exception: classes a framework must proxy (Spring @Configuration and class-based @Transactional/@Async beans, JPA entities) must stay non-final.
  • Return empty collections, never null. Optional only as a return type: not fields, parameters or elements, and no bare get(). If the project uses JSpecify, follow its annotations.

Errors and resources

  • No empty catch, no e.printStackTrace(), no System.out "handling". Log through the project's logger and recover, or rethrow with the cause attached. An intentionally ignored exception is named ignored (or _ on 22+) and gets a comment explaining why.
  • InterruptedException: propagate it, or call Thread.currentThread().interrupt() before translating it. Never swallow it. For APIs called from request handlers, translating to an unchecked exception after restoring the flag is usually friendlier than a checked throws.
  • try-with-resources for every AutoCloseable scoped to a method. Long-lived ones, such as a component's executor, close at shutdown.

Concurrency

  • Blocking I/O fan-out on 21+ → virtual threads (Executors.newVirtualThreadPerTaskExecutor()); never pool them; cap a fragile downstream with a Semaphore.
  • ExecutorService.close() waits for submitted tasks to finish. On 25 that includes tasks invokeAll already cancelled. A per-call try (var ex = …) therefore doesn't bound latency when a callee ignores interrupts, and many HTTP/JDBC clients do. For deadline-bound fan-out, keep a long-lived executor (shut down at exit with shutdownNow() plus a bounded awaitTermination) and use invokeAll(tasks, timeout, unit), which cancels stragglers at the deadline. Don't call f.get(2, SECONDS) in a loop: the worst case is N × 2s. Cancelled-but-uninterruptible calls keep running in the background, so tell the user the client's own connect/read timeouts are what actually bound them.
  • When the code runs on JDK 21–23, don't block inside synchronized on virtual threads (it pins the carrier); use ReentrantLock. JDK 24+ fixed this. The runtime JDK decides, not --release.
  • Check-then-act on shared state needs an atomic operation: Set.add's return value, putIfAbsent, computeIfAbsent. A ConcurrentHashMap doesn't make if (!m.containsKey(k)) m.put(k, v) safe.
  • ScopedValue (25) replaces ThreadLocal for context passed down a call chain. It is not inherited by tasks you submit to an executor, only by StructuredTaskScope forks, which are preview. Rebind it inside the task if needed. MDC, security and transaction context still live in ThreadLocals today.

Pitfalls models hit with modern Java

TrapWhat happensDo instead
Arrow-form switch statement over an enumNot checked for exhaustiveness. A missing case compiles and silently does nothing.Use a switch expression. On 21+, adding case null -> throw … makes the statement exhaustiveness-checked too
default in a switch over a sealed type or enum you ownHides new variants from the compilerLeave default out. For third-party or externally sourced enums, tolerating unknown constants is correct
Wrapped one-line prose ("a " + "b") turned into a text blockEvery source line break becomes \n, a closing """ on its own line adds a trailing \n, and the common leading indentation, including a space that started a piece, is stripped. Tool descriptions, messages and test expectations change silentlyEnd each line with \ and put the space before it; put the closing """ on the last content line; write a leading space on the first line as \s. Prove the value is unchanged (compare the old and new constants)
Code compiled against an old sealed hierarchyNew subtype at runtime → MatchExceptionRecompile dependents; treat new variants as breaking
Stream.toList() vs Collectors.toList() vs toUnmodifiableList()toList() is unmodifiable but allows nulls; toUnmodifiableList() throws NPE on null; Collectors.toList() makes no mutability promiseUse toList() only when callers don't mutate; else toCollection(ArrayList::new)
List.of / List.copyOf / Map.ofReject null elements; List.of(..).contains(null) throws NPE; Map.of throws on duplicate keysFilter nulls first or use another collection; toMap(k, v, merge) for duplicates
Collections.unmodifiableList(list)A view: later changes to list show throughList.copyOf(list) for a snapshot
Record with an array componentequals/hashCode compare the array by referenceUse List, or override both
list.reversed() (21)A live view, not a copyList.copyOf(list.reversed()) for a snapshot
getFirst() on an empty listNoSuchElementExceptionCheck isEmpty()
Optional.orElse(expensive())The argument is evaluated even when a value is presentorElseGet(() -> expensive())
Integer a == bReference comparison; works only for −128..127equals, or primitives
new BigDecimal(0.1)Captures the binary error (0.1000000000000000055…)new BigDecimal("0.1") / BigDecimal.valueOf(0.1)
Shared static SimpleDateFormatCorrupted output under concurrencyA DateTimeFormatter constant
One RandomGenerator from RandomGeneratorFactory (e.g. L64X128MixRandom) shared across threadsThese algorithms aren't thread-safeOne instance per thread, or ThreadLocalRandom.current()
javax.xml.bind (JAXB), Nashorn, reflection into java.* internalsRemoved from the JDK (11, 15) or blocked since 17: fails at runtime, not always at compile timeExplicit Jakarta/Nashorn dependencies; supported APIs (see modern-java.md#avoid)

Step 3 — Workflow by task

Writing new code. Find the baseline (Step 1). Design the types first, then the behavior. Add tests for the behavior. Then verify (below).

Verify, don't assume. Run the project's build (./mvnw verify, ./gradlew build, or the system mvn/gradle if there's no wrapper). With no build, compile with javac --release <N> -Xlint:all, adding -cp for any dependencies. Use --release, not -source: it also rejects APIs newer than N, such as List.getFirst() under 17. A clean compile at the right release proves Step 1 held.

Refactoring and modernizing existing code. Preserve observable behavior, because that's the contract.

  • If there are no tests, first write characterization tests against the original code, then keep them green.
  • Target the project's baseline unless the user asked for an upgrade. Change one concern at a time.
  • Sweep the mechanical idioms the baseline already allows, even when the release isn't changing. Seeing records and pattern switch in a codebase doesn't mean the sweep was done, so grep for the old forms (patterns in references/modern-java.md#idioms). Each conversion keeps behavior:
    • string literals concatenated across lines → a text block, including annotation attributes (a text block is a compile-time constant). Wrapped one-line prose stays one line only if you use \ at each line end; see Pitfalls;
    • JSON, XML, SQL or YAML packed onto one line, in a text block or an escaped literal ("{\"id\":1}") → a text block laid out the way a reader scans it (nested structure indented, one XML element per line). Do this only where the consumer ignores that whitespace, such as a parser, Solr's update handler, or a test fixture that is parsed before it is asserted on. Leave strings that are compared or forwarded verbatim as they are, such as tool descriptions, golden-file expectations and signed payloads. Prove it by parsing the old and new forms and comparing the values;
    • instanceof T followed by a (T) cast → instanceof T t;
    • a statement switch that only assigns or returns → a switch expression;
    • manual finally { close() } → try-with-resources; raw types → generics; explicit type arguments → <>;
    • collect(Collectors.toList()) whose result is never mutated → toList().
  • Keep public signatures source-compatible unless the user asked for API changes. Modernize behind them: generics, try-with-resources, enums, and BigDecimal/java.time internally. Records are for new internal types.
  • Fix real bugs even if behavior shifts, such as a missing hashCode, swallowed exceptions, leaks, or null meaning "none". List each one.
  • Offer contract changes as a follow-up with a migration path. Examples: double → BigDecimal return types, a mutable class → record, Date → Instant in signatures. The usual path is a new method next to a @Deprecated old one.
  • Watch for new overloads that make existing calls ambiguous. For example, adding m(Category) beside m(String) breaks m(null).
  • In the summary, separate breaks callers' compilation, runtime behavior changes, and kept on purpose.

Upgrade order and OpenRewrite recipes: references/modern-java.md#upgrade.

Reviewing.

  • Order findings by severity: correctness and concurrency bugs first, then API and design, then a short modernization and style list. Short means one line per idiom from the Step 3 sweep, with a count and an example file:line, not one line per site. Short doesn't mean leaving idioms out.
  • For each finding give file:line, the concrete consequence (what breaks, for whom), and the fix. End with the minimum set to fix before merge.
  • Cite an Effective Java item (EJ 11) only where the reasoning is non-obvious; tagging every line is noise.
  • Don't rewrite the code unless asked, and don't nitpick what the formatter owns. The formatter owns where lines wrap. Whether a string is a + chain or a text block is your call, not the formatter's.

Step 4 — Self-check

  • Every feature is final in the project's release (or preview is enabled), and the code compiled at that release.
  • Every switch over an enum or sealed type you own is an exhaustive expression or pattern switch with no default.
  • Concurrent code: deadlines actually bound latency; check-then-act is atomic.
  • Refactors: public signatures unchanged unless asked, and every behavior change listed.
  • Refactor, modernize and review passes: grepped for every mechanical idiom in Step 3, then converted or reported each one. Converted strings are identical to the originals, and reformatted JSON/XML payloads parse to the same values.

References

  • references/modern-java.md: Java 17 → 25 feature guide. JEPs, BAD/GOOD code, preview and withdrawn APIs, and a safe upgrade order. Read it when using any feature newer than Java 11, or when upgrading code.
  • references/effective-java.md: all 90 Effective Java (3rd ed.) items marked Applies / Refined / Superseded, each with its modern note, plus worked before/after examples (tagged class → sealed, value class → record, virtual-thread fan-out with deadlines, and more). Read it when reviewing, or when you need the reasoning behind a default.

相關技能