GENESIS; Let there be Java code!
Find a file
Elex 0085a57953 Expand README with detailed inline examples for builder APIs
- Added comprehensive examples for `ClassBuilder` features, including field, method, constructor generation, and nested class handling.
- Demonstrated advanced capabilities such as nested generics, wildcard types, structured control flow (if-else, loops, try-catch), and in-memory compilation.
- Updated sections to improve clarity and showcase practical usage scenarios with direct code snippets.
2026-07-20 14:56:34 +09:00
.idea Introduce GenesisCompiler: Dynamic In-Memory Compilation and Execution Framework 2026-07-20 13:47:52 +09:00
build-logic Initialize project with Gradle build and source structure 2026-07-20 02:39:53 +09:00
compiler Introduce GenesisCompiler: Dynamic In-Memory Compilation and Execution Framework 2026-07-20 13:47:52 +09:00
gradle Introduce advanced builder APIs and generic type support for code generation 2026-07-20 04:22:58 +09:00
let-there-be-code Add inline code examples to builder classes for improved API clarity and documentation 2026-07-20 14:35:38 +09:00
.gitattributes Initialize project with Gradle build and source structure 2026-07-20 02:39:53 +09:00
.gitignore Initialize project with Gradle build and source structure 2026-07-20 02:39:53 +09:00
genesis.png Remove WritableCodeSpec interface and refactor references in specs and SourceWriter 2026-07-20 14:12:23 +09:00
gradle.properties Initialize project with Gradle build and source structure 2026-07-20 02:39:53 +09:00
gradlew Initialize project with Gradle build and source structure 2026-07-20 02:39:53 +09:00
gradlew.bat Initialize project with Gradle build and source structure 2026-07-20 02:39:53 +09:00
LICENSE Initialize project with Gradle build and source structure 2026-07-20 02:39:53 +09:00
README.md Expand README with detailed inline examples for builder APIs 2026-07-20 14:56:34 +09:00
REQUIREMENTS.md Initialize project with Gradle build and source structure 2026-07-20 02:39:53 +09:00
settings.gradle.kts Introduce GenesisCompiler: Dynamic In-Memory Compilation and Execution Framework 2026-07-20 13:47:52 +09:00

Genesis

Genesis는 외부 의존성 없이(Zero-Dependency) Java 21 이상의 환경에서 고속으로 자바 소스 코드를 생성하기 위한 라이브러리입니다. 복잡한 AST(Abstract Syntax Tree) 탐색 대신 StringBuilder와 직관적인 템플릿 방식을 채택하여 메모리 효율과 렌더링 속도를 극대화했습니다.

GENESIS


주요 특징 (Key Features)

  • Java 21+ 최적화: Record, Switch Pattern Matching, Markdown JavaDoc 등 최신 자바 문법을 내부 구현 및 생성 코드에 적극 활용합니다.
  • Zero-Dependency: 어떠한 외부 라이브러리 의존성 없이 순수 JDK API만으로 동작합니다.
  • Fluent Builder API: 코드 작성 순서에 구애받지 않는 자유로운 메서드 체이닝 스타일의 빌더를 제공합니다.
  • 자동 임포트 관리 (Auto-Import): Class<?> 타입을 직접 인자로 전달하면 필요한 임포트 구문을 자동으로 수집, 정렬 및 생성합니다. (java.lang.* 자동 제외)
  • 고속 렌더링 엔진: StringBuilder 기반의 스트림 라이팅 방식을 사용하여 대량의 코드 생성 시에도 뛰어난 성능을 보장합니다.
  • 인메모리 컴파일 지원: 생성된 코드를 파일로 저장하지 않고 즉시 메모리에서 컴파일하여 Class<?> 객체로 로드할 수 있는 기능을 제공합니다.

시작하기 (Getting Started)

ClassBuilder userClass = Genesis.createClass("com.elex_project.model", "User")
        .publicModifiers()
        .field(f -> f.modifiers("private", "final").type(String.class).name("name"))
        .field(f -> f.modifiers("private", "final").type(int.class).name("age"))
        
        // 생성자 정의
        .constructor(c -> c
                .publicModifiers()
                .parameter(String.class, "name")
                .parameter(int.class, "age")
                .statement("this.name = name;")
                .statement("this.age = age;")
        )
        
        // Getter 메서드 정의
        .method("getName", Set.of("public"), String.class, m -> m
                .statement("return this.name;")
        );

String code = Genesis.build(userClass.build(), userClass.getImportedTypes());
System.out.println(code);

위의 코드를 실행하면 이렇게 생성됩니다.

package com.elex_project.model;

public class User {
    private final String name;
    private final int age;

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return this.name;
    }
}

요구 사양

  • JDK 21 이상

설치 (Gradle)

repositories {
    maven {
        name = "Elex Repository"
        url = uri("https://artifacts.elex-project.com/repository/maven/")
    }
}
dependencies {
    implementation("com.elex-project:genesis:1.0.0") // 자바 코드 빌더
    implementation("com.elex-project:genesis-compiler:1.0.0") // 옵션) 인메모리 컴파일러
}

사용 예시 (Usage Examples)

1. 기본 클래스 생성 (Class Generation)

Genesis.createClass를 통해 클래스 구조를 정의하고 렌더링할 수 있습니다.

ClassBuilder builder = Genesis.createClass("com.example", "OrderProcessor")
    .publicModifiers()
    .annotate(Deprecated.class)
    .field(f -> f.modifiers("private", "final")
        .type(List.class, String.class)
        .name("orders")
        .initializer("new {}<>()", ArrayList.class))
    .method("processAll", Set.of("public"), void.class, m -> m
        .parameter(String.class, "id")
        .statement("System.out.println(\"Processing: \" + id);")
        .conditionIf(i -> i
            .ifBranch("orders.isEmpty()", ib -> ib.statement("return;"))
        )
        .statement("orders.clear();")
    );

String sourceCode = Genesis.write(builder);
System.out.println(sourceCode);

2. 레코드 생성 (Record Generation)

Java 21의 record 구조도 간편하게 생성 가능합니다.

RecordBuilder builder = Genesis.createRecord("com.example", "User")
    .publicModifiers()
    .component(p -> p.type(Long.class).name("id"))
    .component(p -> p.type(String.class).name("name"))
    .method("isValid", Set.of("public"), boolean.class, m -> m
        .statement("return id != null && !name.isBlank();")
    );

String sourceCode = Genesis.write(builder);

3. 중첩 제네릭 및 와일드카드

와일드카드(? extends, ? super) 및 다중 경계 타입(T extends Serializable & AutoCloseable)을 완벽히 지원합니다.

ClassBuilder repositoryClass = Genesis.createClass("com.elex_project.repository", "DataRepository")
        .publicModifiers()
        // 복합 제네릭 메서드 시그니처: <T extends Serializable & AutoCloseable>
        .method("processData", Set.of("public", "static"), "void", m -> m
                .typeParameter(t -> t.raw("T")
                        .extendsBound(Serializable.class)
                        .andBound(AutoCloseable.class))
                .parameter(p -> p.raw(List.class)
                        .argument(w -> w.wildcard().extendsBound(Number.class)), "numbers")
                .statement("// logic here")
        );

4. 람다 기반 구조적 제어 흐름 (Nested Control Flow)

중첩 블록 깊이에 따른 들여쓰기 공백(4-spaces)이 자동 누적되어 정교한 가독성을 제공합니다.

classBuilder.method("executeTask", Set.of("public"), void.class, m -> m
		.parameter(List.class, "items")
        .tryCatch(t -> t
		    .tryBlock(tryScope -> tryScope
		        .loop("for (Object item : items)", loopScope -> loopScope
		            .conditionIf(ifScope -> ifScope
		                .ifBranch("item == null", ib -> ib.statement("continue;"))
		                .elseBranch(eb -> eb
		                    .conditionSwitch("item.hashCode()", sw -> sw
		                        .caseLabel("1", cb -> cb.statement("System.out.println(\"One\");"))
		                        .defaultLabel(db -> db.statement("System.out.println(\"Default\");"))
		                    )
		                )
		            )
		        )
		    )
		    .catchBlock(IOException.class, "e", catchScope -> catchScope
		        .statement("e.printStackTrace();")
            )
        )
    );

5. 중첩 클래스 (Inner / Static Nested Class)

부모 빌더의 임포트 레지스트리를 자동으로 전파받아 이너 클래스 내부의 타입 선언도 최상위 파일로 수집됩니다.

ClassBuilder builder = Genesis.createClass("com.example", "Outer")
        .publicModifiers()
        .nestedClass("InnerBuilder", inner -> inner
                .modifiers("public", "static")
                .field(f -> f.modifiers("private").type(Map.class).name("cache"))
        );

6. 인메모리 컴파일 (In-Memory Compilation)

생성된 소스 코드를 즉시 실행 가능한 클래스로 변환할 수 있습니다.

ClassBuilder builder = Genesis.createClass("com.example.dynamic", "Calculator")
		.publicModifiers()
		.method("add", Set.of("public"), int.class, m -> m
				.parameter(int.class, "a")
				.parameter(int.class, "b")
				.statement("return a + b;")
		);

// 1. 인메모리 컴파일 수행
GenesisCompiler compiler = new GenesisCompiler();
Class<?> compiledClass = compiler.compile(builder);

// 2. 리플렉션 실행
Object instance = compiledClass.getDeclaredConstructor().newInstance();
var addMethod = compiledClass.getMethod("add", int.class, int.class);
Object result = addMethod.invoke(instance, 10, 20); // Result: 30

프로젝트 구조 (Project Structure)

  • let-there-be-code: 빌더 API 및 렌더링 엔진 핵심 로직.
  • compiler: 인메모리 컴파일을 위한 컴포넌트.

Copyright © 2026 Elex Project. All rights reserved.

이 프로젝트는 LICENSE 파일의 약관을 따릅니다.

https://www.elex-project.com