codeconsole commented on code in PR #15732:
URL: https://github.com/apache/grails-core/pull/15732#discussion_r3416488630


##########
grails-web-core/src/main/groovy/org/grails/web/servlet/HttpServletRequestExtension.groovy:
##########
@@ -251,4 +252,26 @@ class HttpServletRequestExtension {
     static Date date(HttpServletRequest request, String name, 
Collection<String> formats) {
         TypeConverters.toDate(request.getAttribute(name), formats)
     }
+    /**
+     * Null-safe, typed read of an attribute. Returns the attribute when it is 
an
+     * instance of {@code type}; otherwise {@code null}. No coercion is 
attempted —
+     * use the named converters ({@code string}, {@code int}, ...) for type 
conversion.
+     */
+    static <T> T getAttribute(HttpServletRequest request, String name, 
Class<T> type) {
+        if (type == null) {
+            throw new IllegalArgumentException('type must not be null - use 
getAttribute(name) for an untyped read')
+        }
+        Object value = request.getAttribute(name)
+        Class<T> resolvedType = (Class<T>) 
ClassUtils.resolvePrimitiveIfNecessary(type)
+        resolvedType.isInstance(value) ? resolvedType.cast(value) : null

Review Comment:
   Proxies are fine with `isInstance` — added a test covering both mechanisms: 
a JDK dynamic proxy (its runtime-generated class implements the interface, so 
`isInstance(interface)` is true) and a subclass (the relationship CGLIB / 
ByteBuddy / Hibernate-lazy proxies use — `isInstance` walks the class hierarchy 
the same way whether the subclass is generated at runtime or declared). Both 
resolve; a wrong-type request still reads as `null` rather than an unsafe cast.
   
   `value.class.isAssignableFrom(type)` would actually break the proxy case — a 
proxy's class is a *subtype* of the proxied type, so it returns false even when 
the value is a valid instance.
   



-- 
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]

Reply via email to