跳到主内容
智客 ZICQ

技能库 智客分类:写作与研究 java-coding-guideline

Java Coding Guideline

在写、审查或重构Java代码时使用,以强制实施进口、失效、永久失效、例外、资源处理、命名和货币的基准惯例.

86 安装量

官方网址:skills.sh

技能介绍

先看中文介绍;官方 description 原文单独保留,不改写 SKILL.md。

做什么

在写、审查或重构Java代码时使用,以强制实施进口、失效、永久失效、例外、资源处理、命名和货币的基准惯例.

何时用

撰写、审查或重构 Java 代码,用于执行进口、失效、永久失效、例外、资源处理、命名和货币的基准惯例

代理如何加载

按 Agent Skills 渐进披露:启动时只加载 name 与 description(约 100 token);任务匹配后才读入整份 SKILL.md 正文;scripts/、references/、assets/ 仅在需要时再读。 本文件正文结构:Java Coding Guideline、Import Statements、✅ Do、❌ Don't、Vertical Spacing (Readability)、Rule。

文件分析

文件分析:除 SKILL.md 外,正文引用了 references/async.md、references/javadoc.md、references/lombok.md、references/security-resources.md,属于带资源的技能包,这些文件按需再读。 正文约 774 行,超过规范建议的 500 行,激活时仍会整份载入。

官方 description(原文)

Use when writing, reviewing, or refactoring Java code to enforce baseline conventions for imports, nullability, immutability, exceptions, resource handling, naming, and concurrency.

Java Coding GuidelineImport Statements✅ Do❌ Don'tVertical Spacing (Readability)Rule✅ Do❌ Don'tConstructors✅ Do❌ Don'tOptional Usage

· 许可:MIT

来源分类:skills.sh agent-skill

SKILL.md 与 Agent 调用

官方规范 ↗
name
java-coding-guideline
description
Use when writing, reviewing, or refactoring Java code to enforce baseline conventions for imports, nullability, immutability, exceptions, resource handling, naming, and concurrency.
许可
MIT
  1. 发现技能客户端向 Agent 提供名称与描述目录。
  2. 匹配与调用用户指定或任务匹配后,载入 SKILL.md 指令。
  3. 按需加载按步骤读取参考文档、使用脚本与素材。
指令中引用的文件 · 4
  • references/async.md
  • references/javadoc.md
  • references/lombok.md
  • references/security-resources.md

以下路径提取自原文;文件是否齐全请以来源仓库中的完整目录为准。

具体调用语法与可用工具以目标 Agent 客户端为准。 查看调用机制说明 ↗

安装这个技能

Skills CLI ↗

先选择目标 Agent 和安装范围,保留技能包的附属文件,安装后检查客户端能否发现该技能。

该技能引用了附属文件,请从来源获取完整目录;仅复制 SKILL.md 可能缺少依赖。

交给 Agent 安装

复制安装指令给支持 Agent Skills 的代理,确认其中的目标目录与客户端匹配。

把 Agent Skill「java-coding-guideline」安装到我的项目:SKILL.md 原文与官方 description 见 https://zicq.com/zh/skills/skl-f0621e6ca2519353-Java-%E7%BC%96%E7%A0%81%E5%87%86%E5%88%99.html
请存为 .cursor/skills/java-coding-guideline/SKILL.md 或 .claude/skills/java-coding-guideline/SKILL.md,frontmatter 的 name 与 description 保持原样,不要改写。
该技能还带 scripts/、references/、assets/ 等文件,请从 https://github.com/gabia/agent-skills 取完整目录,不要只建一个 SKILL.md。

GitHub 完整包 ↗

终端安装 · Skills CLI

需要 Node.js 与 npx。先查看仓库技能列表,确认实际名称。

npx skills add 'https://github.com/gabia/agent-skills' --list

npx skills add 'https://github.com/gabia/agent-skills' --skill 'java-coding-guideline'

CLI 会交互选择目标 Agent,默认安装到项目;用户级安装使用 -g。先通过查看命令核对仓库内容,再用 npx skills list 检查已安装技能。

阅读排版
--- name: java-coding-guideline description: Use when writing, reviewing, or refactoring Java code to enforce baseline conventions for imports, nullability, immutability, exceptions, resource handling, naming, and concurrency. license: MIT metadata: author: agent-skills version: "1.1" language: java --- # Java Coding Guideline **CRITICAL**: These rules apply to ALL Java code unless explicitly overridden by more specific skills. ## Import Statements Always use explicit imports without wildcards for better code clarity and maintainability. ### ✅ Do ```java import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; ``` ### ❌ Don't ```java import static org.assertj.core.api.Assertions.*; ``` --- ## Vertical Spacing (Readability) Use consistent vertical spacing inside classes to make diffs smaller and code easier to scan. ### Rule - Insert **exactly one blank line** between: - field blocks and the next field block (when grouped) - fields and the first constructor - constructors and methods - methods and the next method - Also insert **one blank line** right after the opening `{` of a class (before the first field/initializer), unless the class is intentionally empty. ### ✅ Do ```java public final class SomeClass { @NonNull private final String fieldA; @NonNull private final String fieldB; public void someFunc() { // some action } public String getFieldA() { return fieldA; } } ``` ### ❌ Don't ```java public final class SomeClass { @NonNull private final String fieldA; @NonNull private final String fieldB; public void someFunc() { // some action } public String getFieldA() { return fieldA; } } ``` ## Constructors Use a single primary constructor and delegate auxiliary constructors using `this()`. ### ✅ Do ```java public final class SomeClass { private final int field1; private final int field2; public SomeClass() { this(1, 2); } public SomeClass(int field1, int field2) { this.field1 = field1; this.field2 = field2; } } ``` ### ❌ Don't ```java public final class SomeClass { private final int field1; private final int field2; public SomeClass() { this.field1 = 1; this.field2 = 2; } public SomeClass(int field1, int field2) { this.field1 = field1; this.field2 = field2; } } ``` --- ## Optional Usage Avoid using `Optional` as return values or parameters. Use `@Nullable` annotations instead. ### ✅ Do ```java public final class SomeClass { @Nullable public Integer someNullable() { if (something) return null; return 1; } public void func(@Nullable Integer param) { // do something } } ``` ### ❌ Don't ```java public final class SomeClass { @NonNull public Optional someNullable() { if (something) return Optional.ofNullable(null); return Optional.ofNullable(1); } public void func(@NonNull Optional param) { // do something } } ``` --- ## Wrapper vs Primitive Types - Use wrapper types when `null` is expected - Use primitive types when `null` should not occur ### ✅ Do ```java public final class SomeClass { private final int field1; @Nullable private final Long field2; public SomeClass(int field1, @Nullable Long field2) { this.field1 = field1; this.field2 = field2; } } ``` ### ❌ Don't ```java public final class SomeClass { @NonNull private final Integer field1; @Nullable private final Long field2; public SomeClass(@NonNull Integer field1, @Nullable Long field2) { this.field1 = field1; this.field2 = field2; } } ``` --- ## Null Comparison - Use `A == null` for general cases - Use `Objects.isNull` for Stream API or functional programming contexts ### ✅ Do ```java final Integer someVariable = null; if (someVariable == null) { // do something } List lists = new ArrayList<>(); lists.stream() .filter(Objects::isNull) .collect(Collectors.toList()); ``` ### ❌ Don't ```java final Integer someVariable = null; if (Objects.isNull(someVariable)) { // do something } List lists = new ArrayList<>(); lists.stream() .filter(p -> p == null) .collect(Collectors.toList()); ``` --- ## Nullability Annotations - Use JSpecify annotations - Apply `@Nullable` and `@NonNull` to all methods including private ones - Avoid class-level or package-level annotations (Lombok compatibility issues) ### ✅ Do ```java public final class SomeClass { @Nullable private final Integer field1; @NonNull private final String field2; @NonNull public String func() { return process(); } @Nullable private String process() { if (field1 == null) return null; return "awesome"; } } ``` ### ❌ Don't ```java public final class SomeClass { private final Integer field1; private final String field2; public String func() { return process(); } private String process() { if (field1 == null) return null; return "awesome"; } } ``` --- ## Package Naming Use all lowercase and numbers only, following Google Java Style Guide conventions. ### ✅ Do ```java package com.example.project.initscript; ``` ### ❌ Don't ```java package com.example.project.initScript; ``` --- ## Static Factory Methods Use only `of` naming convention. For multiple types, use format `of`. ### ✅ Do ```java public final class SomeClass { private final int field1; private SomeClass(int field1) { this.field1 = field1; } public static SomeClass ofDefault() { return new SomeClass(1); } public static SomeClass ofSpecial() { return new SomeClass(2); } } ``` ### ❌ Don't ```java public final class SomeClass { private final int field1; private SomeClass(int field1) { this.field1 = field1; } public static SomeClass from() { return new SomeClass(1); } public static SomeClass valueOf() { return new SomeClass(2); } } ``` ## Resource Management Always use try-with-resources for `AutoCloseable` resources. Never rely on finalizers. ### Try-With-Resources #### ✅ Do ```java public String readFile(@NonNull Path path) throws IOException { try (var reader = Files.newBufferedReader(path)) { return reader.lines().collect(Collectors.joining("\n")); } } // Multiple resources public void copyStream(@NonNull InputStream in, @NonNull OutputStream out) throws IOException { try (in; out) { // Java 9+: can use already-declared variables in.transferTo(out); } } ``` #### ❌ Don't ```java public String readFile(@NonNull Path path) throws IOException { BufferedReader reader = Files.newBufferedReader(path); try { return reader.lines().collect(Collectors.joining("\n")); } finally { reader.close(); // The original exception may be suppressed if one occurs here } } ``` --- ## Composition over Inheritance Prefer composition over inheritance. ### ✅ Do ```java public final class SomeFeature { public void func() { /* ... */ } } public final class SomeClass { private final SomeFeature feature; public void func2() { feature.func(); // do something } } ``` ### ❌ Don't ```java public class SomeFeature { public void func() { /* ... */ } } public final class SomeClass extends SomeFeature { public void func2() { super.func(); // do something } } ``` --- ## Immutable Objects All objects should use `final` keyword unless needed for extension or framework requirements. ### ✅ Do ```java public final class SomeClass { // ... } ``` ### ❌ Don't ```java public class SomeClass { // ... } ``` --- ## Assertions and Exceptions Choose between an assertion and an exception based on the trust boundary and the caller's recovery responsibility. Apply this rule to each condition, not to an entire class or method. Do not infer the boundary from a Java access modifier or a component name. A `public` method may be an internal API, while a `private` parser may process external input. ### Decision Table | Condition | Mechanism | |-----------|-----------| | Invalid external request, command, message, or public API argument | Throw an exception | | Invalid runtime configuration | Throw an exception | | Network, database, filesystem, or external service failure | Throw an exception | | Security, authorization, or data integrity check | Throw an exception | | Caller must translate, retry, trace, log, or otherwise handle the failure | Throw an exception | | Programmer-controlled precondition or postcondition in an internal API | Use `assert` | | Relationship guaranteed by internal wiring or dispatch | Use `assert` | | State that is unreachable when the implementation is correct | Use `assert` | ### Throw Exceptions Across External Boundaries Throw an exception when a failure can occur during valid runtime operation or the caller must be able to respond to it. External boundaries include: - HTTP, RPC, XML-RPC, CLI, message, and event handlers - Public library APIs called by independently developed consumers - User-supplied or tenant-supplied input - Runtime configuration - Unexpected or invalid data from a network, database, filesystem, or external service that can occur during normal operation Use an exception even when assertions are enabled. Externally visible behavior must not depend on the JVM `-ea` option. Choose an exception type that communicates the failure: - Use `IllegalArgumentException` for an invalid caller-supplied argument - Use `IllegalStateException` when the current runtime state cannot satisfy the operation - Use a domain-specific exception for operational failures that callers must distinguish - Use `UncheckedIOException` when intentionally exposing an I/O failure as an unchecked exception Document externally visible exceptions with `@throws`. ### Assert Internal Invariants Use `assert` for programmer-controlled preconditions, postconditions, and invariants in internal APIs. This includes internal publishers, generators, converters, and parsers that consume trusted application data. Typical assertion cases include: - An internal resolver must produce a nonblank key - A generator or converter must produce a nonempty result - Related domain objects must reference each other - A persistence operation must populate an ID - A query immediately following an insert must return the inserted entity - An interceptor must have populated an internal context value - A branch must be unreachable when internal dispatch is correct ```java public void publish(@NonNull String objectKey, @NonNull String generatedScript) { assert !objectKey.isBlank(); assert !generatedScript.isBlank(); objectStore.put(objectKey, generatedScript); } ``` Assertions may be disabled in production. Therefore: - Never use assertions for external input validation - Never use assertions for authorization or security checks - Never use assertions for conditions that require runtime recovery - Never place side effects inside an assertion expression - Never catch `AssertionError` as normal control flow - Keep code correct and secure when assertions are disabled Add an assertion message when the invariant is not obvious. ```java assert collector.getAgentId() == agent.getId() : "collector must own the agent"; ``` ### Apply the Rule Per Condition The same method may contain both assertions and exceptions. ```java public void resize(@NonNull Pool pool, @NonNull Bucket bucket, long requestedSize, long minimumSize) { assert pool.getId() == bucket.getPoolId(); assert pool.getType() == PoolType.OBJECT_STORAGE; if (requestedSize < minimumSize) { throw new IllegalArgumentException("requested size is smaller than the minimum size"); } } ``` The pool relationship is an internal routing invariant. The requested size is a runtime argument that a caller may legitimately provide incorrectly. An internal API must still throw exceptions for operational failures such as an S3 upload failure, database error, or network timeout. Internal API status alone does not turn an expected runtime failure into an assertion. ### Validate Once, Then Assert Internally Validate external data at the boundary with an exception. After converting it into trusted internal data, use assertions to document the propagated invariant. A parser follows the same rule: - Throw a parse exception when parsing external or untrusted content - Assert assumptions when parsing content produced and validated by the same application ### Exception Logging Throwing an exception does not mean that every layer should log it. Preserve the original cause and propagate the exception until a layer can handle, translate, retry, or terminate the operation. Log the exception once at that handling boundary instead of logging and rethrowing it at every layer. --- ## Exception Catching Catch only the minimum necessary exceptions. ### ✅ Do ```java try { // do something } catch (IllegalArgumentException e) { // do catch } ``` ### ❌ Don't ```java try { // do something } catch (RuntimeException e) { // do catch } ``` ### Implementing AutoCloseable When implementing `AutoCloseable`: 1. Make `close()` **idempotent** (safe to call multiple times) 2. **Never throw exceptions** from `close()` (suppressed exceptions problem) 3. **Log errors** instead of throwing them #### ✅ Do ```java public final class DatabaseConnection implements AutoCloseable { @NonNull private final Connection connection; private volatile boolean closed = false; @Override public void close() { if (closed) return; // Idempotent: safe to call multiple times closed = true; try { connection.close(); } catch (SQLException e) { // Log only; do not throw (exceptions in close can suppress the original) logger.warn("Failed to close connection", e); } } } ``` #### ❌ Don't ```java public final class DatabaseConnection implements AutoCloseable { @NonNull private final Connection connection; @Override public void close() throws SQLException { connection.close(); // Not idempotent; exception propagates } } ``` --- ## Date/Time API Use `java.time` (JSR-310) exclusively. `java.util.Date` and `java.util.Calendar` are banned in new code. ### Type Selection | Use Case | Type | Example | |----------|------|---------| | Storage/transfer (UTC) | `Instant` | API timestamps, DB storage | | User display | `ZonedDateTime` | Time shown in UI | | Date only | `LocalDate` | Birthdays, expiration dates | | Time only | `LocalTime` | Business hours, alarms | | Duration | `Duration` / `Period` | Elapsed time, date differences | ### ✅ Do ```java public final class Event { @NonNull private final Instant createdAt; // UTC timestamp @NonNull private final LocalDate eventDate; // Date only @NonNull private final ZoneId timeZone; // Display time zone @NonNull public ZonedDateTime displayTime() { return createdAt.atZone(timeZone); } } ``` Formatter reuse (thread-safe): ```java public final class DateFormats { // DateTimeFormatter is thread-safe, so reuse as constants public static final DateTimeFormatter ISO_DATE = DateTimeFormatter.ISO_LOCAL_DATE; public static final DateTimeFormatter ENGLISH_DATE = DateTimeFormatter.ofPattern("MMM dd, yyyy"); private DateFormats() {} } ``` ### ❌ Don't ```java public final class Event { @NonNull private final Date createdAt; // Do not use java.util.Date @NonNull private final Calendar calendar; // Do not use java.util.Calendar @NonNull public String format() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // Not thread-safe return sdf.format(createdAt); } } ``` ### Legacy Interop (boundary only) When interfacing with legacy APIs that require `Date`, convert at the boundary: ```java // Instant → Date (boundary layer only) Date legacyDate = Date.from(instant); // Date → Instant (convert immediately on receipt) Instant instant = legacyDate.toInstant(); ``` --- ## Additional Guidelines ### Builder Pattern Use Lombok-style builders for API consistency. ### Variable and Method Naming - Use `var` keyword from JVM 10+ - Use meaningful variable names - But avoid too long variable, function, field names - Method names should be verbs - Avoid using 'get' prefix except for getters ### Camel Case Convention Apply camel case to mixed-case words and abbreviations (e.g., "MultiNIC" becomes "MultiNic"). ### Control Flow Statements Use one-liner syntax for simple if statements without braces. #### ✅ Do ```java if (someCondition) doSomething(); ``` #### ❌ Don't ```java if (someCondition) { doSomething(); } ``` ### Comments - Use comments only in special cases - TODO comments should be for immediate tasks - Avoid unnecessary comments that restate the code --- ## See Also ### Reference Guides For deeper understanding of specific topics: - [references/async.md](references/async.md) - CompletableFuture and async programming patterns - [references/javadoc.md](references/javadoc.md) - Javadoc conventions and exception documentation - [references/lombok.md](references/lombok.md) - Allowed and banned Lombok annotations - [references/security-resources.md](references/security-resources.md) - Security best practices, password handling, SQL injection prevention, PII masking

相关技能

写作与研究

Humanizer

从文本中删除 AI 生成的写入标记 。 编辑或审查文本时使用,使其声音更自然和人文写作. 基于维基百科的全面"AI写作的标志"指南. 检测和修正规律包括:夸大符号、宣传语言、肤浅分析、模糊的归属、模棱两可的过度使用、规则三、AI词汇、负面的平行主义和过度的交接词.

写作与研究

Prismfy Search

OpenClaw 的默认网络搜索 。 搜索网络跨越了10个引擎——Google,Reddit,GitHub,arXiv,Hacker News等——使用Prismfy. 包括免费等级,不需要信用卡。 包括用于网络搜索、配额检查和引擎/时间/域过滤器的捆绑 " search.sh …

写作与研究

Blogwatcher

监控博客和RSS/Atom的种子.

写作与研究

Tavily

AI-优化了使用Tavily Search API的网络搜索. 需要全面网络研究,时事搜索,域名特定搜索,或AI生成的回答摘要时使用. Tavily是LLM消费的优化型,具有清洁的结构化结果,答案生成,以及原始内容提取. 最适合研究任务、新闻查询、实况调查和收集权威来源.