codeconsole opened a new pull request, #15732:
URL: https://github.com/apache/grails-core/pull/15732
## Summary
Follow-up to #15715. The named converters (`string`, `int`, `boolean`, …)
cover scalar attribute values, but attributes frequently hold richer objects —
a security principal, a domain instance, a CSRF token — where today the only
statically-compilable read is a cast at every call site:
```groovy
CsrfToken token = (CsrfToken) session.getAttribute('_csrf')
UserDetails user = request.getAttribute(USER_ATTRIBUTE) as UserDetails
```
This adds a `Class`-typed overload of `getAttribute` (plus a default-value
variant) to `session`, `request` and `servletContext`:
```groovy
CsrfToken token = session.getAttribute('_csrf', CsrfToken)
UserDetails user = request.getAttribute('apiUser', UserDetails)
Theme theme = session.getAttribute('theme', Theme, Theme.DEFAULT)
```
The generic signature (`static <T> T getAttribute(holder, String name,
Class<T> type)`) lets the static compiler infer the return type from the class
literal, so the read compiles under `@CompileStatic` / `@GrailsCompileStatic`
with no cast.
## Design
- **Typed read, not coercion.** The attribute is returned only when it is an
instance of the requested type; absent and wrong-typed attributes read as
`null` (so the default-value overload also applies on a type mismatch). No
`TypeConverters` delegation — the named converters remain the coercing API, the
`Class` overload is the type-safe retrieval API. Two simple contracts instead
of one mixed one.
- **Overloads `getAttribute` rather than introducing a new verb.** Mirrors
`grails.config.Config.getProperty(String key, Class<T> targetType, T
defaultValue)` (and Spring's `Environment.getProperty(key, type, default)`),
and shows up in IDE completion right next to the raw `getAttribute(String)`.
- **Scope: the three attribute holders only.** `flash` is skipped — it is a
`Map`, and Groovy's DGM `Map.get(key, default)` (which *inserts* the default)
makes a two-arg sibling on flash a semantic trap. `params` is skipped — its
values are Strings, where a non-coercing typed read is not useful.
## Tests & docs
- `HttpSessionExtensionSpec`, `HttpServletRequestExtensionSpec`,
`ServletContextExtensionSpec` each gain two features: instance-match /
supertype-match / absent / wrong-type-reads-as-null semantics, default-value
behavior, and a `@CompileStatic` static-resolution guard (the guard fails test
compilation without the new extension methods).
- New "Typed Reads of Attributes" subsection in the controllers guide,
following the "Type Conversion of Attributes" section from #15715.
`:grails-web-core:test` passes in full.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]