Skip to content

Library Usage

Damian Malczewski edited this page Sep 10, 2026 · 1 revision

Library Usage

The core generator, :modelmaker, is a plain library with no build-tool API. Use it directly when the Gradle plugin is not an option - a Maven build, an Ant task, a custom tool, or a test that asserts on generated source.

dependencies {
    implementation("io.github.malczuuu:modelmaker:<version>")
}

It is a JPMS module (io.github.malczuuu.modelmaker), requires com.google.gson, and takes org.jspecify as an optional (requires static) dependency.

The pipeline

schema files → SchemaLoader → List<ModelType> → ModelMaker.emit(type) → source text
  • SchemaLoaders - factory for the loader. createDelegatingSchemaLoader() dispatches by file extension.
  • SchemaLoader - load(List<Path>) returns List<ModelType>, validating and cross-checking every $ref.
  • ModelType - the resolved model: a top-level type plus nested types for inline objects.
  • ModelOptions - the feature flags, see Feature Configuration.
  • SchemaException - thrown for every schema problem; getFile() names the file, getErrors() lists them all.
  • JavaModelMaker - emit(ModelType) returns the .java source text.
  • KotlinExtensionMaker - emit(ModelType) returns the <Name>Extensions.kt source text.

Minimal example

File schemasDir = ...;
File outputDir = ...;

List<Path> schemas = Files.walk(schemasDir.toPath())
    .filter(path -> Files.isRegularFile(path))
    .filter(path -> path.getFileName().toString().endsWith(".json"))
    .collect(Collectors.toList());

if (schemas.isEmpty()) {
    return;
}

JavaModelMaker javaModelMaker = new JavaModelMaker(ModelOptions.builder().build());

SchemaLoaders.createDelegatingSchemaLoader().load(schemas).forEach(
    type -> {
        String javaSrc = javaModelMaker.emit(type);
        write(outputDir, type.getPackageName(), type.getName() + ".java", javaSrc);
    });

write is yours - create outputDir/<package as directories>/<Name>.java and write the text. The generator produces source text only; it never touches the file system.

Configuring features

ModelOptions options = ModelOptions.builder()
    .jackson(true)                                  // shorthand: enabled, annotations on getters
    .validation(
        ValidationConfig.builder()
            .enabled(true)
            .annotateFields(true)
            .annotateGetters(false)
            .build())
    .openApi(OpenApiConfig.builder().enabled(true).build())
    .withers(true)
    .preferPrimitives(true)
    .build();
  • ModelOptions.defaults() is every feature off.
  • jackson(boolean) / validation(boolean) / openApi(boolean) are shorthands that keep the default getter placement; pass a JacksonConfig / ValidationConfig / OpenApiConfig to control placement.
  • mutate() on an existing ModelOptions returns a pre-filled builder for a modified copy.

A schema file's own "features" block is applied on top of these options by emit, per type - the options you pass are the baseline, not the final word. See Feature Configuration.

Kotlin extensions

KotlinExtensionMaker kotlinExtensionMaker = new KotlinExtensionMaker();

types.forEach(type -> {
    String kotlinSrc = kotlinExtensionMaker.emit(type);
    write(outputDir, type.getPackageName(), type.getName() + "Extensions.kt", kotlinSrc);
});

KotlinExtensionMaker takes no options. A type with no properties yields a file with only a package line - skip writing it if you prefer.

Loading rules

  • Load all schemas in one load(...) call. $ref resolution is cross-checked across the list, so loading files one at a time makes every cross-file reference fail.
  • Files are parsed in file-name order, independent of the order you pass them, so output is deterministic.
  • Every schema problem - malformed JSON, a bad keyword, an unresolvable $ref, an unsupported extension - throws SchemaException. Messages are on Troubleshooting.
  • A load reports all the problems it finds, not just the first. getErrors() on the thrown exception lists them individually, each with the getFile() it came from:
try {
    types = SchemaLoaders.createDelegatingSchemaLoader().load(schemas);
} catch (SchemaException e) {
    e.getErrors().forEach(error -> log.error("{}: {}", error.getFile(), error.getMessage()));
    throw e;
}

Reusing a maker

JavaModelMaker holds nothing but the options it was constructed with - every emit call resolves its own effective options from the schema's "features" block - so one instance can be reused freely, including from several threads. KotlinExtensionMaker has no state at all.

Output details

The emitted text is already laid out the way the plugin writes it - sorted single-type imports (never a wildcard), a // Generated by ModelMaker ... notice, and a trailing newline. Don't run a formatter over it: some lines, @Schema and container-element annotations in particular, are deliberately long, and reformatting only creates churn against the next regeneration. Exclude the output directory from Spotless or its equivalent instead.

Clone this wiki locally