skip to content

A Retrofit service compiles, yet one endpoint throws IllegalArgumentException on its first call; how does create() turn the interface into requests, and how do you catch such declaration errors earlier?

level: seniorimportance: should knowfreq 35%

answer

  1. a dynamic proxy, not codegen
  2. parsed on first call
  3. cached per method
  4. an eager switch on the builder
  5. a test that calls create

basics

~20 s

Retrofit.create() returns a java.lang.reflect.Proxy that parses each method's annotations on its first call and caches the result, so a bad declaration fails only when that method runs. validateEagerly(true) parses every method inside create(), which a unit test can exercise.

solid answer

~40 s

`retrofit.create(IssueService::class.java)` checks that the type is an interface without type parameters and returns a dynamic `Proxy`. No code is generated. The first time a method is invoked, Retrofit parses its annotations and parameter types, resolves its call adapter and converter, and caches the result per `Method`; a mistake such as `@DELETE` with a `@Body` throws `IllegalArgumentException` ("Non-body HTTP method cannot contain @Body") at that moment, possibly on a rarely used screen. `Retrofit.Builder.validateEagerly(true)` moves that parsing into `create()` for every declared method. Because it costs reflection at startup, teams usually enable it in debug builds or in a JVM unit test that builds the real `Retrofit` and calls `create()` for each service. The fix for that example is `@HTTP(method = "DELETE", path = "...", hasBody = true)`.

code

kotlin · 19 lines
kotlin
interface IssueService {
    @HTTP(method = "DELETE", path = "projects/{projectId}/labels", hasBody = true)
    suspend fun removeLabels(
        @Path("projectId") projectId: String,
        @Body labels: LabelIds,
    ): Unit
}

class IssueServiceDeclarationTest {
    @Test
    fun declarationsParse() {
        val retrofit = Retrofit.Builder()
            .baseUrl("https://tracker.example.com/api/v2/")
            .addConverterFactory(productionConverterFactory())
            .validateEagerly(true)
            .build()
        retrofit.create<IssueService>()
    }
}

go deeper

for a junior

Recall that create() returns an implementation of your interface at runtime, built from the annotations.

for a middle

Explain the dynamic proxy, the lazy parse with a per-method cache, and the IllegalArgumentException message that names the method.

for a senior

Show how you move declaration errors into a test or debug build with validateEagerly, and what eager validation still cannot see.

for a principal

Decide the guardrail: a declaration test for every service interface in CI, one Retrofit instance per client, and eager validation kept out of release startup.

## What create() actually returns Retrofit has no annotation processor. `Retrofit.create(Class)` (or the Kotlin extension `retrofit.create<IssueService>()`) does two things: 1. **Validates the type**: it must be an interface (`API declarations must be interfaces.`), and neither it nor any interface it extends may declare type parameters. 2. **Returns a `java.lang.reflect.Proxy`** whose invocation handler receives every call. Methods declared by `Object` are handled directly, interface default methods are invoked as written, and every other method is looked up in a cache of parsed **service methods**. The cache is a `ConcurrentHashMap` keyed by `Method`. On a miss, Retrofit parses that one method: the HTTP method annotation, the relative URL and its `{blocks}`, every parameter annotation, the call adapter for the return type and the converters for the request and response bodies. Since Retrofit 2.10.0 the parse is locked per method rather than per class, so a burst of first calls to different methods does not contend. ## Why the error appears late Because parsing is **lazy**, a broken declaration compiles, `create()` succeeds, and the failure waits until the method is first called. The exception is an `IllegalArgumentException` whose message ends with `for method IssueService.removeLabels`, which points straight at the declaration. Typical causes: | Message | Cause | |---|---| | `Non-body HTTP method cannot contain @Body.` | a `@Body` on `@GET` or `@DELETE` | | `URL "..." does not contain "{issueID}".` | a `@Path` name that is not in the template | | `A @Path parameter must not come after a @Query.` | parameter order | | `HTTP method annotation is required (e.g., @GET, @POST, etc.).` | a method with no HTTP annotation | | `Only one HTTP method is allowed. Found: GET and POST.` | two method annotations | | `HEAD method must use Void or Unit as response type.` | a `@HEAD` returning a body | | `Unable to create converter for ...` | no registered converter accepts the response type | The first row has a Retrofit-specific fix. Retrofit treats `DELETE` as a method without a body. When a server expects one, declare the method with `@HTTP(method = "DELETE", path = "projects/{projectId}/labels", hasBody = true)` and keep the `@Body` parameter. ## Catching errors before users do **`Retrofit.Builder.validateEagerly(true)`** makes `create()` parse every method the interface declares, skipping default, static and synthetic ones, so any declaration error surfaces at creation. Two ways to use it: - **In debug builds**: `validateEagerly(BuildConfig.DEBUG)`. Errors appear the first time a developer launches the app, without paying the reflection cost in release, where `create()` often runs during startup. - **In a JVM unit test**: build the `Retrofit` instance with the same converter and call adapter factories as production, enable eager validation and call `create()` for each service interface. The test needs no network, and it fails the build instead of a screen. Two limits of eager validation are worth knowing: 1. It walks the methods the interface **declares** (`getDeclaredMethods`), so methods inherited from a parent interface are still parsed on first call. 2. It validates declarations, not runtime values. A `null` `@Path` argument, a `@Path` value of `..`, or a `{block}` that no parameter fills are not caught, because Retrofit only checks that each `@Path` name appears in the template, not the reverse. ## Interfaces and instances The proxy is cheap to call but the parse is not free, and the cache lives on the `Retrofit` instance. Services created repeatedly from one instance share its parsed methods, but a `Retrofit` built per screen, or a new one from `newBuilder()`, starts with an empty cache and parses everything again. Create the `Retrofit` once and each service once from it, typically in the dependency graph. ## Worked example The issue tracker's "remove labels" endpoint is `DELETE projects/{projectId}/labels` with a JSON list in the body. Declared with `@DELETE` and `@Body`, it compiled and passed code review, and crashed the first time a user removed a label. A unit test that builds the production `Retrofit` with `validateEagerly(true)` and calls `create<IssueService>()` fails on that declaration at once; switching to `@HTTP(..., hasBody = true)` makes it pass. ## What interviewers listen for - **Proxy plus reflection**, not generated code. - **Lazy parsing with a per-method cache**, which explains the late failure. - `validateEagerly` and a unit test as the way to move the failure left. - The `@HTTP` escape hatch for a body on `DELETE`.

  • Why not turn on validateEagerly in release builds as well?
    It makes `create()` reflect over and parse every declared method, including resolving converters and call adapters, at the moment the service is created, which is often during app startup. A test or a debug build already catches the declaration errors, so release builds can keep the lazy, pay-on-first-call behaviour.
  • Will eager validation catch a {issueId} block that no @Path parameter fills?
    No. Retrofit checks that every `@Path` name appears in the template, but not that every template block has a parameter. The unfilled block is sent as literal text in the URL, so it shows up as a server error, not a validation failure.

  • Retrofit generates the service implementation at compile time.
  • A wrong annotation on a service method fails the build.
  • @DELETE accepts a @Body like @POST does.
  • validateEagerly also checks the arguments each call passes.
  • Building a new Retrofit per screen costs nothing extra.

Assumes Retrofit 3.0.0; per-method parse locking and skipping synthetic methods in eager validation date from 2.10.0.