본문으로 건너뛰기
cccskills
무료GitHub에 공개

java-developer

Guide for developing on the Java 21 baseline, including modern features, best practices, and integration with Groovy/Grails projects

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md7.2 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

<!-- SPDX-License-Identifier: Apache-2.0 Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0. -->

What I Do

  • Provide guidance on Java 21 syntax, features, and APIs for use in Grails/Groovy projects.
  • Assist with code generation, refactoring, and debugging using modern Java features like records, sealed classes, pattern matching, and text blocks.
  • Recommend best practices for Java code that interoperates with Groovy in mixed-language projects.
  • Guide on tooling: Gradle builds, JDK setup, testing with JUnit 5/Spock, and profiling.

When to Use Me

Use this skill when working on Java code within this repository, especially for:

  • Writing Java classes that will be used alongside Groovy code.
  • Implementing features using records, sealed classes, or pattern matching for instanceof.
  • Migrating older Java code (e.g., Java 8/11/17) to Java 21 idioms.
  • Performance optimization, security hardening, or module system (JPMS) questions.
  • Understanding how Java code integrates with Groovy's dynamic features.

Java 21 Baseline Features

Records (JEP 395)

Immutable data carriers with auto-generated constructors, accessors, equals, hashCode, and toString:

public record Book(String title, String author, int year) {
    // Compact constructor for validation
    public Book {
        if (title == null || title.isBlank()) {
            throw new IllegalArgumentException("Title cannot be blank");
        }
    }
}

Sealed Classes (JEP 409)

Restrict which classes can extend or implement a type:

public sealed interface Shape permits Circle, Rectangle, Triangle {
    double area();
}

public final class Circle implements Shape {
    private final double radius;
    public Circle(double radius) { this.radius = radius; }
    public double area() { return Math.PI * radius * radius; }
}

public non-sealed class Rectangle implements Shape {
    // Can be further extended
}

Pattern Matching for instanceof (JEP 394)

Eliminate redundant casts:

// Before pattern matching
if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.length());
}

// Modern Java
if (obj instanceof String s) {
    System.out.println(s.length());
}

Text Blocks (JEP 378)

Multi-line string literals with proper formatting:

String json = """
    {
        "name": "Grails",
        "version": "7.0"
    }
    """;

String sql = """
    SELECT id, name, created_at
    FROM users
    WHERE status = 'ACTIVE'
    ORDER BY created_at DESC
    """;

Switch Expressions (JEP 361)

Use switch as an expression with arrow syntax:

String result = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> "Relaxed";
    case TUESDAY -> "Productive";
    case THURSDAY, SATURDAY -> "Moderate";
    case WEDNESDAY -> {
        var temp = calculateWorkload();
        yield temp > 5 ? "Busy" : "Normal";
    }
};

Enhanced NullPointerException Messages (JEP 358)

Detailed NPE messages showing exactly which variable was null:

Cannot invoke "String.length()" because "user.getAddress().getCity()" is null

Helpful Stream and Collection APIs

// Stream.toList() - unmodifiable list
List<String> names = users.stream()
    .map(User::getName)
    .toList();

// Collectors improvements
Map<Status, List<User>> byStatus = users.stream()
    .collect(Collectors.groupingBy(User::getStatus));

Java/Groovy Interoperability

Calling Java from Groovy

Groovy seamlessly calls Java code:

// Java record used in Groovy
def book = new Book("Grails Guide", "Author", 2024)
println book.title()  // Groovy can use property syntax too
println book.title    // Also works

Calling Groovy from Java

// Groovy classes are just Java classes
GroovyService service = new GroovyService();
service.process(data);

// Working with Groovy closures in Java
Closure<String> closure = ...;
String result = closure.call("input");

Best Practices for Mixed Projects

  • Use Java for performance-critical code with @CompileStatic equivalent behavior.
  • Use Java records for DTOs shared between Java and Groovy code.
  • Prefer Java interfaces that Groovy classes implement.
  • Avoid Groovy-specific features (like categories) in APIs consumed by Java.

Build and Testing

Gradle Configuration

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

tasks.withType(JavaCompile).configureEach {
    options.encoding = 'UTF-8'
    options.compilerArgs += ['-parameters']  // Preserve parameter names
}

Testing with JUnit 5

@Test
@DisplayName("Book record should validate title")
void bookShouldValidateTitle() {
    assertThrows(IllegalArgumentException.class, () ->
        new Book("", "Author", 2024)
    );
}

@ParameterizedTest
@ValueSource(strings = {"", " ", "  "})
void blankTitlesShouldBeRejected(String title) {
    assertThrows(IllegalArgumentException.class, () ->
        new Book(title, "Author", 2024)
    );
}

Testing with Spock (from Groovy)

def "Java record should work in Spock tests"() {
    when:
    def book = new Book("Test", "Author", 2024)

    then:
    book.title() == "Test"
    book.author() == "Author"
}

Performance and Profiling

JVM Options for Java 21

# Recommended GC for most workloads
-XX:+UseG1GC

# For low-latency requirements
-XX:+UseZGC

# Memory settings
-Xms512m -Xmx2g

# Enable JFR for profiling
-XX:StartFlightRecording=duration=60s,filename=recording.jfr

Profiling Tools

  • JDK Flight Recorder (JFR): Built-in low-overhead profiler
  • VisualVM: GUI-based monitoring and profiling
  • async-profiler: Low-overhead sampling profiler

Common Patterns

Null Handling with Optional

public Optional<User> findById(Long id) {
    return Optional.ofNullable(repository.get(id));
}

// Usage
String name = findById(id)
    .map(User::getName)
    .orElse("Unknown");

Resource Management with try-with-resources

try (var reader = new BufferedReader(new FileReader(path));
     var writer = new BufferedWriter(new FileWriter(output))) {
    reader.lines()
        .map(String::toUpperCase)
        .forEach(line -> writer.write(line + "\n"));
}

Immutable Collections

// Create immutable collections
List<String> list = List.of("a", "b", "c");
Set<String> set = Set.of("x", "y", "z");
Map<String, Integer> map = Map.of("one", 1, "two", 2);

// Copy to immutable
List<String> copy = List.copyOf(mutableList);

Code Style Guidelines

  • Follow existing patterns in the codebase.
  • Use var for local variables when the type is obvious from context.
  • Prefer records for simple data carriers.
  • Use sealed classes to model restricted type hierarchies.
  • Add @Override annotation when overriding methods.
  • Use meaningful parameter names (preserved with -parameters flag).

Resources

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Expert guide for Gradle 9 builds in apache/grails-core on the 8.0.x line - multi-project topology, convention plugins, BOM platforms, dependency rules, task configuration hygiene, and repo-specific patterns that override generic Gradle docs

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

apache/grails-core2.9천2026년 10월 19일 업데이트

Guide for upgrading Grails applications from Grails 7.x to Grails 8, covering Java 21, Groovy 5 name resolution and static compilation, Spring Boot 4.1, Spring Framework 7, dependency management, Micronaut, Jackson 3, Hibernate 7, TagLibs, testing, content negotiation, asset pipeline wildcard paths, and validation behavior changes

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

apache/grails-core2.9천2026년 10월 19일 업데이트

Comprehensive guide for Grails development, covering web applications, REST APIs, GORM, controllers, services, views, plugins, and testing with Spock and Geb

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

apache/grails-core2.9천2026년 10월 19일 업데이트

Expert guide for Groovy 5 development, covering concise syntax, closures, DSLs, metaprogramming, static compilation, and integration with Java 21 and Grails

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

apache/grails-core2.9천2026년 10월 19일 업데이트

Guide for working in the grails-data-hibernate7 module, especially Hibernate 7 domain binding, mapping migration, generators, and integration tests. Use this when changing code or tests under grails-data-hibernate7.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

apache/grails-core2.9천2026년 10월 19일 업데이트

Step-by-step process for merging a previously-standalone Grails plugin repository (e.g. grails-spring-security, grails-redis) into the grails-core monorepo as one or more Gradle subprojects, wiring it into the shared build, publishing, docs, and CI the same way the existing modules are.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

apache/grails-core2.9천2026년 10월 19일 업데이트

apache의 스킬 모두 보기

이 스킬의 문제 신고