
# Only what runs: introspection

The `ObjectMapper`, validation, data binding and SpEL need to read and set the properties of your classes, create instances and call methods by name. Java does that with reflection. Dart has no reflection on Flutter, the web or AOT executables, so the generator writes a description of each class instead: an `Introspection` with closures that read a property, set it, call the constructor, call a method.

A description is of a class (an `@Introspected` class, or one the build finds in use), not of a bean. That is why the types are named `Introspection`, `Introspector`, `IntrospectedProperty`, `IntrospectedMethod`, `IntrospectedConstructor` and `IntrospectedParameter`: "bean" stays the container's word. The old `Bean...` names are deprecated typedefs of these for one release. `BeanWrapper` keeps its name, as in Spring, and the context's introspector is still the bean `beanIntrospector`.

The generator does not describe every part of every class. It describes a class **only for what the application does with it**, as far as the build can see.

## Why

A full description of a class has a getter closure and a setter closure for each property, a constructor description with every parameter, and a closure per method. In an app with many DTOs that adds up, and most of it never runs: a request body is only created and filled, never read back as JSON; a response is only read, never created by the framework.

Each closure is code the compiler must keep, because it cannot know the closure is never called. So the build leaves out what it saw nothing use. The description says what it holds, and code that needs a missing part fails with a message that names the class, the part and the fix.

## The parts

| Part | What it is in the description | Written when the class is |
|---|---|---|
| getters | `IntrospectedProperty.get` | written out: turned into JSON, read by an expression, bound from configuration |
| constructor and setters | `IntrospectedConstructor`, `instantiate`, `IntrospectedProperty.set`, `fromJson` | read in: created from JSON, bound from a request or from configuration |
| the getters of constrained properties | `get` of only the properties with a constraint, `@Valid()` or `@Each()` | validated |
| methods | `IntrospectedMethod` | the target of an expression that may call its methods |

The annotations of the class and the list of its properties (names, types, annotations) are always written.

## What asks for each part

| Use in the application | Parts |
|---|---|
| A controller's return type (also inside `Future`, `Stream`, `ResponseEntity`, `Page`), an `@ExceptionHandler`'s answer | getters, and constructor and setters (a test reads the answer back with `mapper.readValue<BookDto>(res.body)`, and `test/` is not scanned) |
| `@RequestBody`, `@RequestPart` | constructor and setters |
| `@RequestBody @Valid()` | constructor and setters, and the getters of the constrained properties |
| A WebSocket `@OnMessage` handler | the message: constructor and setters; the reply: getters |
| A client's arguments (Feign, `@WebSocketClient`) | getters |
| A client's answer | constructor and setters |
| `@ConfigurationProperties` | getters, and constructor and setters (the binder sets the properties and reads their current values, to bind nested objects in place) |
| `mapper.readValue<T>`, `treeToValue<T>`, `readList<T>`, `readMap<T>` | `T`: constructor and setters |
| `mapper.writeValueAsString(v)`, `valueToTree(v)` | the static type of `v`: getters |
| `mapper.convertValue<T>(v)` | `v`: getters; `T`: constructor and setters |
| A WebSocket session's `sendJson(v)`, the registry's `broadcast(pattern, v)` | the static type of `v`: getters |
| `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, `@PostFilter` | the arguments (when the expression names `#name`, `#p0`, `#a0`, `args`, or `filterObject` for `@PreFilter`) or the result (`returnObject`, `filterObject`): getters and methods; `target`: the bean itself |
| `@Cacheable`, `@CachePut`, `@CacheEvict`, `@Caching` (key, condition, unless) | the same: the arguments, the result (`#result`), the bean (`target`) |
| A `@Query` with a `:#{...}` the build does not compile (data starter) | the classes the expression reaches: getters and methods |
| `@JsonValue`, `@JsonAnyGetter`, `@JsonAnySetter` | the method they mark (with the getters, or the setters) |
| `@JsonInclude(JsonInclusion.nonDefault)` on a class that is written out | also constructor and setters: the mapper compares each value with the one of a new instance |
| A method with an annotation of your own `@BeanMethodAnnotation()` | everything of its parameter and return types: the build does not know what your framework does with them |
| `@Scheduled`, `@Secured`, WebSocket `@OnOpen`, `@OnClose`, `@OnError` | nothing |
| A class listed by `@JsonView` | nothing: it is only known |

## Unions, and what a class is made of

A class reached by several uses gets the **union** of their parts. A class that is both a response and a request body gets getters and constructor and setters.

What a class is made of takes the same parts as the class: the types of its properties, the types of its constructor parameters, the type argument of `Page<BookDto>`, the subtypes listed by `@JsonSubTypes`. A response `Order` with a property `List<OrderLine> lines` describes `OrderLine` for writing out too.

## Calls of the `ObjectMapper`

The build reads your calls of the mapper and uses their **static types**:

```dart
final book = mapper.readValue<Book>(json);      // Book: read in
final text = mapper.writeValueAsString(order);  // Order: written out
final copy = mapper.convertValue<Dto>(entity);  // Dto: read in; the entity's class: written out
```

Three limits:

- Only classes of the package of the call are described. A class of another package is listed in `@Introspected(classes: [...])`.
- A value of static type `Object` or `dynamic` names no class. `mapper.writeValueAsString(value as Object)` describes nothing.
- `sendJson` and `broadcast` count only in a library that imports `spring_boot_starter_websocket`; elsewhere they are other methods (`StreamController.broadcast`).

## `@Introspected`: everything

`@Introspected()` on a class asks for every part, and so does a class listed in `@Introspected(classes: [...])`. What those classes are made of gets every part as well. Use it when a class is used where the build cannot see it: a value passed as `Object`, a class only a plugin reads, a class of another package.

```dart
@Introspected()
class Report {
  Report(this.title);
  final String title;
  String summary() => title.toUpperCase();
}

// Classes of other packages: listed on any class of the scanned package.
@Introspected(classes: [Money, Address])
class IntrospectionConfig {}
```

## What the description says it holds

Each description lists its parts in `Introspection.parts`, a `Set<IntrospectionPart>`:

| `IntrospectionPart` | Means |
|---|---|
| `read` | the getters |
| `write` | the constructor, `instantiate`, the setters and `fromJson` |
| `methods` | the methods an expression may call |

A description with all three parts leaves `parts:` out (the default is all three). `describesPart(part)` tells whether a part is there.

### Example: a validated request body

Input:

```dart
class NewBook {
  const NewBook({required this.isbn, required this.title, this.stock = 0});

  @NotBlank()
  @Size(min: 4, max: 13)
  final String isbn;

  @NotBlank()
  final String title;

  @PositiveOrZero()
  final int stock;
}

@RestController()
@RequestMapping('/api/books')
class BookController {
  BookController(this.books);

  final BookService books;

  @PostMapping()
  Future<ResponseEntity<Book>> create(
    @RequestBody() @Valid() NewBook book,
  ) async {
    final created = await books.create(book);
    return ResponseEntity.created(Uri.parse('/api/books/${created.isbn}'))
        .body(created);
  }
}
```

Output (from the web starter's test application, prefixes dropped). `NewBook` is read in and validated: a constructor, and a getter for each constrained property. All three properties have constraints, so all three have a getter. There are no setters (the fields are `final`) and no methods:

```dart
const Introspection<NewBook>(
  className: r'NewBook',
  properties: [
    IntrospectedProperty<NewBook>(
      r'isbn',
      typeInfo: ClassType<String>(),
      get: _$get68,
      annotations: [NotBlank(), Size(min: 4, max: 13)],
    ),
    IntrospectedProperty<NewBook>(
      r'title',
      typeInfo: ClassType<String>(),
      get: _$get69,
      annotations: [NotBlank()],
    ),
    IntrospectedProperty<NewBook>(
      r'stock',
      typeInfo: ClassType<int>(),
      get: _$get70,
      annotations: [PositiveOrZero()],
    ),
  ],
  parts: {IntrospectionPart.write},
  constructor: IntrospectedConstructor<NewBook>(
    parameters: [
      IntrospectedParameter(
        r'isbn',
        type: ClassType<String>(),
        symbol: #isbn,
        isRequired: true,
      ),
      IntrospectedParameter(
        r'title',
        type: ClassType<String>(),
        symbol: #title,
        isRequired: true,
      ),
      IntrospectedParameter(
        r'stock',
        type: ClassType<int>(),
        symbol: #stock,
        hasDefaultValue: true,
        defaultValue: 0,
      ),
    ],
    create: _$create71,
  ),
),
```

The closures are top-level functions (`_$get68`, `_$create71`), so the whole description is a constant.

### Example: a reply that is only written out

```dart
class Shout {
  const Shout(this.text);
  final String text;
}

@WebSocketEndpoint('/ws/echo/{name}')
class EchoEndpoint {
  @OnMessage()
  Shout echo(@PathVariable() String name, String text, Principal? user) =>
      Shout('$name: ${text.toUpperCase()}');
}
```

```dart
const Introspection<Shout>(
  className: r'Shout',
  properties: [
    IntrospectedProperty<Shout>(
      r'text',
      typeInfo: ClassType<String>(),
      get: _$get75,
    ),
  ],
  parts: {IntrospectionPart.read},
),
```

No constructor, no setter: nothing in the app creates a `Shout` from JSON.

## When a missing part is used

Code that needs a part the build left out throws an `IntrospectionPartError` (a `StateError`). It never returns an empty object or skips the values silently. The message names the class, the missing part, what needed it and the fix:

```text
Bad state: Book is described without its getters, but it is written out as
JSON. The build described only what it saw used, and did not see that: add
@Introspected() to Book.
```

The uses the runtime names in that message:

| Message ends with | Part |
|---|---|
| `it is written out as JSON` | getters |
| `it is read in from JSON` | constructor and setters |
| `it is written with JsonInclusion.nonDefault, which compares each value with the one of a new instance` | constructor and setters |
| `an instance is created`, `an instance is created for a nested property` | constructor and setters |
| `its fields are bound from the input`, `the form is bound to an instance of it` | constructor and setters |

Typical causes: a value cast to `Object` before it is written as JSON, a class read by a library that is not part of the scan, a class of another package. The fix is always the same: `@Introspected()` on the class, or the class in `@Introspected(classes: [...])`.

## Where the descriptions are

The descriptions of a module are in a library of their own, `lib/spring_gen/<library>.spring.introspection.dart`, beside the module's `.spring.dart`. It has a getter `$<module>Introspections` (`$appBeansIntrospections`), a getter so that a hot reload yields the descriptions of the new code. The `.spring.dart` imports it and hands the list to the module; so the module's file holds the beans and the wiring, not thousands of lines of descriptions.

The descriptions only the `@ConfigurationProperties` binder uses are in `<library>.spring.properties.dart` (`$<module>PropertiesIntrospections`). A class that the binder and something else use stays with the others.

A unit test registers the descriptions without starting a context:

```dart
import 'package:my_app/spring_gen/src/app.spring.introspection.dart';

void main() {
  setUpAll(() => Introspector.shared.registerAll($appIntrospections));
}
```

The same file holds what [the object methods](../../spring-core-dart/beans/object-methods.md) (`@EqualsAndHashCode`, `@ToString`, `@CopyWith`) generate: the annotated class is described, and its `==`, `hashCode` and `toString()` are functions in `Introspection.objectMethods`.

Inside the generator, introspection has its own scanner, model and emitter (`core/introspection/`). The bean scan and the parts of the packages (web, WebSocket, data) tell it what a class needs, and it writes the descriptions.

## See also


- [Optimizations overview](index.md)
- [Build speed](build-speed.md)
- [Bean definitions](../bean-definitions.md)
- [Object methods](../../spring-core-dart/beans/object-methods.md)
- [JSON](../../spring-core-dart/json/index.md)
- [SpEL](../../spring-core-dart/spel/index.md)
- [Validation constraints](../../spring-core-dart/validation/constraints.md)
