Skip to content

Commit b619003

Browse files
authored
Implement JsonCreator factory generic type variable handling (#2895)
Previously TypeVariable handling worked in most cases due to coincidence, in most cases the type variable names used in factory methods and types use the same name, and order. However the way this worked resulted in bugs in edge cases, and was relatively fragile because it wasn't intended in the first place. Now we attempt to map type variables from the requested type through the factory function regardless of matching type variable names.
1 parent 49c744d commit b619003

File tree

5 files changed

+723
-6
lines changed

5 files changed

+723
-6
lines changed

src/main/java/com/fasterxml/jackson/databind/introspect/AnnotatedCreatorCollector.java

+10-3
Original file line numberDiff line numberDiff line change
@@ -219,7 +219,10 @@ private List<AnnotatedMethod> _findPotentialFactories(TypeFactory typeFactory,
219219
// 27-Oct-2020, tatu: SIGH. As per [databind#2894] there is widespread use of
220220
// incorrect bindings in the wild -- not supported (no tests) but used
221221
// nonetheless. So, for 2.11.x, put back "Bad Bindings"...
222-
final TypeResolutionContext typeResCtxt = _typeContext;
222+
// final TypeResolutionContext typeResCtxt = _typeContext;
223+
224+
// 03-Nov-2020, ckozak: Implement generic JsonCreator TypeVariable handling [databind#2895]
225+
final TypeResolutionContext emptyTypeResCtxt = new TypeResolutionContext.Empty(typeFactory);
223226

224227
int factoryCount = candidates.size();
225228
List<AnnotatedMethod> result = new ArrayList<>(factoryCount);
@@ -244,7 +247,7 @@ private List<AnnotatedMethod> _findPotentialFactories(TypeFactory typeFactory,
244247
if (key.equals(methodKeys[i])) {
245248
result.set(i,
246249
constructFactoryCreator(candidates.get(i),
247-
typeResCtxt, mixinFactory));
250+
emptyTypeResCtxt, mixinFactory));
248251
break;
249252
}
250253
}
@@ -254,8 +257,12 @@ private List<AnnotatedMethod> _findPotentialFactories(TypeFactory typeFactory,
254257
for (int i = 0; i < factoryCount; ++i) {
255258
AnnotatedMethod factory = result.get(i);
256259
if (factory == null) {
260+
Method candidate = candidates.get(i);
261+
// Apply generic type information based on the requested type
262+
TypeResolutionContext typeResCtxt = MethodGenericTypeResolver.narrowMethodTypeParameters(
263+
candidate, type, typeFactory, emptyTypeResCtxt);
257264
result.set(i,
258-
constructFactoryCreator(candidates.get(i),
265+
constructFactoryCreator(candidate,
259266
typeResCtxt, null));
260267
}
261268
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
package com.fasterxml.jackson.databind.introspect;
2+
3+
import com.fasterxml.jackson.databind.JavaType;
4+
import com.fasterxml.jackson.databind.type.TypeBindings;
5+
import com.fasterxml.jackson.databind.type.TypeFactory;
6+
7+
import java.lang.reflect.Method;
8+
import java.lang.reflect.ParameterizedType;
9+
import java.lang.reflect.Type;
10+
import java.lang.reflect.TypeVariable;
11+
import java.lang.reflect.WildcardType;
12+
import java.util.ArrayList;
13+
import java.util.Objects;
14+
15+
/**
16+
* Internal utility functionality to handle type resolution for method type variables based on the requested
17+
* result type.
18+
*/
19+
final class MethodGenericTypeResolver {
20+
21+
/*
22+
* Attempt to narrow types on a generic factory method based on the expected result (requestedType).
23+
* If narrowing was possible, a new TypeResolutionContext is returned with the discovered TypeBindings,
24+
* otherwise the emptyTypeResCtxt argument is returned.
25+
*
26+
* For example:
27+
* Given type Wrapper<T> with
28+
* @JsonCreator static <T> Wrapper<T> fromJson(T value)
29+
* When a Wrapper<Duck> is requested the factory must return a Wrapper<Duck> and we can bind T to Duck
30+
* as though the method was written with defined types:
31+
* @JsonCreator static Wrapper<Duck> fromJson(Duck value)
32+
*/
33+
static TypeResolutionContext narrowMethodTypeParameters(
34+
Method candidate,
35+
JavaType requestedType,
36+
TypeFactory typeFactory,
37+
TypeResolutionContext emptyTypeResCtxt) {
38+
TypeBindings newTypeBindings = bindMethodTypeParameters(candidate, requestedType, emptyTypeResCtxt);
39+
return newTypeBindings == null
40+
? emptyTypeResCtxt
41+
: new TypeResolutionContext.Basic(typeFactory, newTypeBindings);
42+
}
43+
44+
/**
45+
* Returns {@link TypeBindings} with additional type information
46+
* based on {@code requestedType} if possible, otherwise {@code null}.
47+
*/
48+
static TypeBindings bindMethodTypeParameters(
49+
Method candidate,
50+
JavaType requestedType,
51+
TypeResolutionContext emptyTypeResCtxt) {
52+
TypeVariable<Method>[] methodTypeParameters = candidate.getTypeParameters();
53+
if (methodTypeParameters.length == 0
54+
// If the primary type has no type parameters, there's nothing to do
55+
|| requestedType.getBindings().isEmpty()) {
56+
// Method has no type parameters: no need to modify the resolution context.
57+
return null;
58+
}
59+
Type genericReturnType = candidate.getGenericReturnType();
60+
if (!(genericReturnType instanceof ParameterizedType)) {
61+
// Return value is not parameterized, it cannot be used to associate the requestedType expectations
62+
// onto parameters.
63+
return null;
64+
}
65+
66+
ParameterizedType parameterizedGenericReturnType = (ParameterizedType) genericReturnType;
67+
// Primary type and result type must be the same class, otherwise we would need to
68+
// trace generic parameters to a common superclass or interface.
69+
if (!Objects.equals(requestedType.getRawClass(), parameterizedGenericReturnType.getRawType())) {
70+
return null;
71+
}
72+
73+
// Construct TypeBindings based on the requested type, and type variables that occur in the generic return type.
74+
// For example given requestedType: Foo<String, Int>
75+
// and method static <T, U> Foo<T, U> func(Bar<T, U> in)
76+
// Produces TypeBindings{T=String, U=Int}.
77+
Type[] methodReturnTypeArguments = parameterizedGenericReturnType.getActualTypeArguments();
78+
ArrayList<String> names = new ArrayList<>(methodTypeParameters.length);
79+
ArrayList<JavaType> types = new ArrayList<>(methodTypeParameters.length);
80+
for (int i = 0; i < methodReturnTypeArguments.length; i++) {
81+
Type methodReturnTypeArgument = methodReturnTypeArguments[i];
82+
// Note: This strictly supports only TypeVariables of the forms "T" and "? extends T",
83+
// not complex wildcards with nested type variables
84+
TypeVariable<?> typeVar = maybeGetTypeVariable(methodReturnTypeArgument);
85+
if (typeVar != null) {
86+
String typeParameterName = typeVar.getName();
87+
if (typeParameterName == null) {
88+
return null;
89+
}
90+
91+
JavaType bindTarget = requestedType.getBindings().getBoundType(i);
92+
if (bindTarget == null) {
93+
return null;
94+
}
95+
// If the type parameter name is not present in the method type parameters we
96+
// fall back to default type handling.
97+
TypeVariable<?> methodTypeVariable = findByName(methodTypeParameters, typeParameterName);
98+
if (methodTypeVariable == null) {
99+
return null;
100+
}
101+
if (pessimisticallyValidateBounds(emptyTypeResCtxt, bindTarget, methodTypeVariable.getBounds())) {
102+
// Avoid duplicate entries for the same type variable, e.g. '<T> Map<T, T> foo(Class<T> in)'
103+
int existingIndex = names.indexOf(typeParameterName);
104+
if (existingIndex != -1) {
105+
JavaType existingBindTarget = types.get(existingIndex);
106+
if (bindTarget.equals(existingBindTarget)) {
107+
continue;
108+
}
109+
boolean existingIsSubtype = existingBindTarget.isTypeOrSubTypeOf(bindTarget.getRawClass());
110+
boolean newIsSubtype = bindTarget.isTypeOrSubTypeOf(existingBindTarget.getRawClass());
111+
if (!existingIsSubtype && !newIsSubtype) {
112+
// No way to satisfy the requested type.
113+
return null;
114+
}
115+
if (existingIsSubtype ^ newIsSubtype && newIsSubtype) {
116+
// If the new type is more specific than the existing type, the new type replaces the old.
117+
types.set(existingIndex, bindTarget);
118+
}
119+
} else {
120+
names.add(typeParameterName);
121+
types.add(bindTarget);
122+
}
123+
}
124+
}
125+
}
126+
// Fall back to default handling if no specific types from the requestedType are used
127+
if (names.isEmpty()) {
128+
return null;
129+
}
130+
return TypeBindings.create(names, types);
131+
}
132+
133+
/* Returns the TypeVariable if it can be extracted, otherwise null. */
134+
private static TypeVariable<?> maybeGetTypeVariable(Type type) {
135+
if (type instanceof TypeVariable) {
136+
return (TypeVariable<?>) type;
137+
}
138+
// Extract simple type variables from wildcards matching '? extends T'
139+
if (type instanceof WildcardType) {
140+
WildcardType wildcardType = (WildcardType) type;
141+
// Exclude any form of '? super T'
142+
if (wildcardType.getLowerBounds().length != 0) {
143+
return null;
144+
}
145+
Type[] upperBounds = wildcardType.getUpperBounds();
146+
if (upperBounds.length == 1) {
147+
return maybeGetTypeVariable(upperBounds[0]);
148+
}
149+
}
150+
return null;
151+
}
152+
153+
/* Returns the TypeVariable if it can be extracted, otherwise null. */
154+
private static ParameterizedType maybeGetParameterizedType(Type type) {
155+
if (type instanceof ParameterizedType) {
156+
return (ParameterizedType) type;
157+
}
158+
// Extract simple type variables from wildcards matching '? extends T'
159+
if (type instanceof WildcardType) {
160+
WildcardType wildcardType = (WildcardType) type;
161+
// Exclude any form of '? super T'
162+
if (wildcardType.getLowerBounds().length != 0) {
163+
return null;
164+
}
165+
Type[] upperBounds = wildcardType.getUpperBounds();
166+
if (upperBounds.length == 1) {
167+
return maybeGetParameterizedType(upperBounds[0]);
168+
}
169+
}
170+
return null;
171+
}
172+
173+
private static boolean pessimisticallyValidateBounds(
174+
TypeResolutionContext context, JavaType boundType, Type[] upperBound) {
175+
for (Type type : upperBound) {
176+
if (!pessimisticallyValidateBound(context, boundType, type)) {
177+
return false;
178+
}
179+
}
180+
return true;
181+
}
182+
183+
private static boolean pessimisticallyValidateBound(
184+
TypeResolutionContext context, JavaType boundType, Type type) {
185+
if (!boundType.isTypeOrSubTypeOf(context.resolveType(type).getRawClass())) {
186+
return false;
187+
}
188+
ParameterizedType parameterized = maybeGetParameterizedType(type);
189+
if (parameterized != null) {
190+
Type[] typeArguments = parameterized.getActualTypeArguments();
191+
TypeBindings bindings = boundType.getBindings();
192+
if (bindings.size() != typeArguments.length) {
193+
return false;
194+
}
195+
for (int i = 0; i < bindings.size(); i++) {
196+
JavaType boundTypeBound = bindings.getBoundType(i);
197+
Type typeArg = typeArguments[i];
198+
if (!pessimisticallyValidateBound(context, boundTypeBound, typeArg)) {
199+
return false;
200+
}
201+
}
202+
}
203+
return true;
204+
}
205+
206+
private static TypeVariable<?> findByName(TypeVariable<?>[] typeVariables, String name) {
207+
if (typeVariables == null || name == null) {
208+
return null;
209+
}
210+
for (TypeVariable<?> typeVariable : typeVariables) {
211+
if (name.equals(typeVariable.getName())) {
212+
return typeVariable;
213+
}
214+
}
215+
return null;
216+
}
217+
218+
private MethodGenericTypeResolver() {
219+
// Utility class
220+
}
221+
}

src/main/java/com/fasterxml/jackson/databind/type/TypeBindings.java

+12-1
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,18 @@ public static TypeBindings create(Class<?> erasedType, JavaType typeArg1, JavaTy
142142
return new TypeBindings(new String[] { vars[0].getName(), vars[1].getName() },
143143
new JavaType[] { typeArg1, typeArg2 }, null);
144144
}
145-
145+
146+
/**
147+
* Factory method for constructing bindings given names and associated types.
148+
*/
149+
public static TypeBindings create(List<String> names, List<JavaType> types)
150+
{
151+
if (names == null || names.isEmpty() || types == null || types.isEmpty()) {
152+
return EMPTY;
153+
}
154+
return new TypeBindings(names.toArray(NO_STRINGS), types.toArray(NO_TYPES), null);
155+
}
156+
146157
/**
147158
* Alternate factory method that may be called if it is possible that type
148159
* does or does not require type parameters; this is mostly useful for

0 commit comments

Comments
 (0)