Redocly/redocly-cli / packages/client-generator/eject-assets/skills/java-generator
java-generator
UnverifiedDesign of the ejected Redocly `java` client generator. Read it, and update it, before changing generators/java/.
The java generator — its skill
This file is the DESIGN of your ejected java generator (generators/java/):
to change the generator, edit this skill first, then make the code match it — a diff
to generators/java/ that has no covering sentence here is incomplete.
What it emits
One self-contained <Stem>.java: a public final class named after the output stem in
PascalCase (client.ts → Client.java, openapi.client.ts → OpenapiClient.java),
because Java puts one public class per file and names the file after it. The class nests
the model records, the enums, the union interfaces, the embedded runtime, and one typed
method per operation. Java ≥ 17 (records, sealed interfaces, instanceof patterns), HTTP
over java.net.http.HttpClient, JSON over the runtime's own reader/writer — zero
dependencies. The package derives from the API title the way the PHP namespace does:
lowercase words run together (Cafe Orders API → package cafeordersapi;), because a
class in the default package cannot be imported from any named package. A title that
cannot be a package as is follows Oracle's package-naming convention — a keyword, or java,
which the JVM keeps for the JDK, gets a trailing underscore (java_, class_); a leading
digit gets a leading underscore (_3dprintingapi); a title with no usable letters becomes
api — and the run warns with the package it used, since the reader cannot see it in the
title. The generator takes no options; a different package is a change to
javaPackageName in an ejected copy.
Design decisions that must hold
- JSON is hand-written in the runtime. Java has no standard JSON library, and a
dependency on one would break the zero-dependency story the other SDKs keep.
Json.parsereads into a plain graph —Map<String, Object>(insertion ordered),List<Object>,String,Longfor integral numbers,Doublefor the rest,Boolean,null— andJson.writeserializes that graph plus the generated types: aJsonValueby itstoJson(), aWireValueby its wire literal, a date by its ISO-8601 text. No streaming parse: a body is read whole, then parsed. - Models are records implementing the runtime's
JsonValue. Every component is a reference type (Long, notlong), so an optional or nullable value is simplynulland a response that omits a required field hydrates instead of crashing. Hydration is compile-time generated per record —static X fromJson(Object json)reads each wire name through the runtime's null-tolerant readers (asString,asLong,asList(…, item -> …),Order.fromJson,Status.fromWire,parsePet), andtoJson()returns aMap<String, Object>of the components (nulls skipped for optionals) thatJson.writeserializes recursively. No reflection.omitschemas hydrate through their base record. - A
writeOnlyproperty is optional even when required: requests and responses share one record, and a response never carries it. - Enums are Java enums implementing
WireValue: members in SCREAMING_SNAKE (the toolkit'senumValuesnames, unique per enum) carrying the wire literal — aStringor aLong— withwire()andfromWire(…), which returnsnullfornulland throwsIllegalArgumentExceptionfor an unknown value. Only string and integer enums get a type; other scalars stay their wire type. - Discriminated unions whose mapping targets are all records become a
sealed interface X extends JsonValuethat each member recordimplements, so a consumer narrows withinstanceofpatterns;parseX(Object json)dispatches on the discriminator and throwsIllegalArgumentExceptionfor an unknown value, since a sealed type has no raw member.permitsis implied: the members sit in the same compilation unit. A union with a target that has no record of its own is typedObject, and itsparseXreturns the raw map for an unknown value. Undiscriminated unions, inline objects, and intersections that do not flatten areObject. allOf is flattened. - Types:
String/Long/Double/Boolean,List<T>,Map<String, T>, record and enum names,Objectfor everything untyped. UnderdateType: Date,date-timeisOffsetDateTimeanddateisLocalDate; hydration goes throughasOffsetDateTime/asLocalDate, and the writer formats a date-time withISO_OFFSET_DATE_TIMEso the seconds never drop out (OffsetDateTime.toString()omits them when zero). - Reserved type names get a
Modelsuffix. Everything nests in one class, so a schema named like a runtime type (Config,Envelope) or a JDK type the runtime references (Thread,List) would shadow it:naming.tsreads those names off the runtime source and renames the schema (ConfigModel). A schema named like the enclosing class itself cannot nest in it at all, and an enclosing class named like a runtime type (an--outputofconfig.ts) would make that name mean the class, so both runs fail with the fix (another--outputname). - Naming: types PascalCase, components and methods camelCase via
identifierFor(..., RESERVED_WORDS.java); a reserved word gets a trailing underscore (class_),+1/-1becomeplus1/minus1, and a digit-leading name gets_. Method names are unique across the client (getUser,getUser2), never one ofObject's methods (getClassbecomesgetClass2), and each name books itsWithHeaders,Pages, andItemsvariants, so a later operation named like one of them moves aside too. - Hand-built comments go through
printer.doc, never a raw/** … */line: a server description or a discriminator value may carry*/or\u, which end or break a Java comment.printer.docwrites*/as*/and every backslash as\u005c, the escape of a backslash, which javac turns back into one without starting another escape — so the Javadoc reads exactly as the description does. - Every path parameter is its own argument, so their names share one namespace with
the locals the method declares itself (
body,params,op,query,url, …). Build them withuniqueIdentifiers(..., { taken: … }): a parameter namedbodybecomesbody2, and the wire name is untouched. Query parameters travel in a<Op>Paramsclass — one nullable public field per parameter with a fluent setter of the same name (new ListOrdersParams().limit(50L)) — because Java has no named arguments;nullfor the whole class sends none. An array parameter repeats the key per element. - Method shape: path parameters first, the body next (
Objectfor an untyped multipart or a binary operation), then<Op>Paramswhen the operation has query parameters. A JSON success returns its type, a non-JSON success (PDF, image, octet stream) returnsbyte[], a bodiless success isvoid, and an SSE operation returnsIterable<ServerSentEvent>. - The operation literal is built where it is used —
Operation op = new Operation(id, method, path, security, pagination)at the top of each method — never a static table of every operation: a single static initializer of a large description (GitHub: ~1000 operations) exceeds the JVM's 64 KB method size. - Errors: unchecked exceptions ARE the error mode.
ApiException(status, url, decoded body) for a non-2xx response,ApiTimeoutExceptionwhen an attempt exceeds the configured timeout,UncheckedIOExceptionfor a transport failure;errorModedoes not change the output (the generator declareserrorModes: ['throw'], soresultfails fast). - Config is a fluent class:
serverUrl,httpClient(an HTTP/1.1 client by default — the JDK default's h2c upgrade attempt confuses servers that do not speak HTTP/2),header(name, value)for every request (aContent-Typehere wins over the description's, matched case-insensitively, so the header is never sent twice),timeoutper attempt,retry(Retry:retriesextra attempts, default 0;delay;strategyfixed or exponential;noJitter;retryOnreplacing the default predicate),middleware(onRequest(HttpRequest.Builder)before each attempt,onResponsein reverse order),idempotencyKeysupplier for POST/PATCH, andauth(Auth:bearer,basic,apiKeyper scheme, each a value or aSupplierresolved per request). - Response headers: an operation that DECLARES success-response headers gains a
<op>WithHeaders()variant returningEnvelope<T>(data,headers— coerced toLong/Double/Boolean/Stringunder camelCase keys, absent or unparsable values omitted — andstatus); a bodiless operation returnsEnvelope<Void>. Operations without declared headers get no variant. - Pagination: a paginated operation gains
<op>Pages()and<op>Items(), bothIterable<T>over the runtime'siterPages, hydrated per page or item throughmapIterable/flattenItems. Eachiterator()starts a fresh request sequence. - Servers: when the description declares servers, a
Serversclass is emitted with one static method per server; server VARIABLES becomeStringarguments, and the description's defaults live in the method's doc comment (Java has no default arguments). The client's baked default staysservers[0]with variable defaults substituted. - Stream bodies pass through. For an untyped
multipart/form-dataoperation or a binary operation the body isObjectand the runtime sorts it out (multipartBody/binaryBody): anInputStreamis sent chunked, in exactly one attempt, whatever the retry policy says, because a consumed stream cannot be replayed; abyte[]orStringis sent raw and keeps the retry policy; a map or a record of an untyped multipart operation is encoded withtoMultipart; any other value of a binary operation is JSON-encoded. The caller'sContent-Type(aConfigheader) wins over the description's or the multipart boundary's. - Parity surface: auth OR-alternatives, retries with
Retry-After+ full-jitter backoff, per-attempt timeouts, idempotency keys, middleware, pagination, SSE (iterSsewithLast-Event-IDreconnect and the server'sretryhint; auth resolves inside the opener, so each reconnect asks a token supplier again), multipart, and theX-Redocly-Clientheader. - The runtime is hand-written in
runtime/Runtime.javain this folder, anabstract class Runtimethat compiles on its own (javac --release 17 -Xlint:all -Werror) and is embedded at prepare time. Inline, the generator copies its class body into the generated class; under--runtime moduleit writes the same source as<Stem>Runtime.java, apublic abstract classthe clientextends, so every runtime name resolves unqualified in both modes and the two cannot drift. Package-private members stay reachable because both classes share one package. - Authored ONLY with the neutral toolkit — the dogfooding guard fails otherwise.
- It documents itself. With
client.docs(or--docs), thedocshook writes<stem>.java.md: the security schemes, then one section per operation with its parameters, body, response type, and behavior notes. The call snippets come from this generator's ownsamplehook, so the page can only show the syntax of the SDK beside it, and the layout comes fromrenderReferencePagein the authoring toolkit — reachable from an ejected copy through@redocly/client-generator.
The modify loop
- Edit this skill: state the new behavior or decision.
- Make
generators/java/match it. - Run
redocly generate-clientand inspect thegit diffof the generated output — generated files are never hand-edited.
Newer built-in versions merge in with redocly eject-generator java --update.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 319k | Updated | Claude CodeCodex | Verified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |