Skip to content

Commit 64d6605

Browse files
committed
Merge pull request #97 from sbrannen/SPR-9493
* SPR-9493: Infer return type of parametrized factory methods
2 parents 9fc05a8 + c461455 commit 64d6605

File tree

7 files changed

+339
-39
lines changed

7 files changed

+339
-39
lines changed

spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2011 the original author or authors.
2+
* Copyright 2002-2012 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -63,6 +63,7 @@
6363
import org.springframework.beans.factory.config.BeanDefinition;
6464
import org.springframework.beans.factory.config.BeanPostProcessor;
6565
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
66+
import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder;
6667
import org.springframework.beans.factory.config.DependencyDescriptor;
6768
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
6869
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
@@ -106,6 +107,7 @@
106107
* @author Mark Fisher
107108
* @author Costin Leau
108109
* @author Chris Beams
110+
* @author Sam Brannen
109111
* @since 13.02.2004
110112
* @see RootBeanDefinition
111113
* @see DefaultListableBeanFactory
@@ -628,16 +630,26 @@ protected Class getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd,
628630
return null;
629631
}
630632

633+
List<ValueHolder> argumentValues = mbd.getConstructorArgumentValues().getGenericArgumentValues();
634+
Object[] args = new Object[argumentValues.size()];
635+
for (int i = 0; i < args.length; i++) {
636+
args[i] = argumentValues.get(i).getValue();
637+
}
638+
631639
// If all factory methods have the same return type, return that type.
632640
// Can't clearly figure out exact method due to type converting / autowiring!
633641
int minNrOfArgs = mbd.getConstructorArgumentValues().getArgumentCount();
634642
Method[] candidates = ReflectionUtils.getUniqueDeclaredMethods(factoryClass);
635-
Set<Class> returnTypes = new HashSet<Class>(1);
643+
Set<Class<?>> returnTypes = new HashSet<Class<?>>(1);
636644
for (Method factoryMethod : candidates) {
637-
if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic &&
638-
factoryMethod.getName().equals(mbd.getFactoryMethodName()) &&
639-
factoryMethod.getParameterTypes().length >= minNrOfArgs) {
640-
returnTypes.add(factoryMethod.getReturnType());
645+
if (Modifier.isStatic(factoryMethod.getModifiers()) == isStatic
646+
&& factoryMethod.getName().equals(mbd.getFactoryMethodName())
647+
&& factoryMethod.getParameterTypes().length >= minNrOfArgs) {
648+
649+
Class<?> returnType = GenericTypeResolver.resolveParameterizedReturnType(factoryMethod, args);
650+
if (returnType != null) {
651+
returnTypes.add(returnType);
652+
}
641653
}
642654
}
643655

spring-beans/src/test/java/org/springframework/beans/factory/support/BeanFactoryGenericsTests.java

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2009 the original author or authors.
2+
* Copyright 2002-2012 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -29,6 +29,8 @@
2929
import java.util.Set;
3030

3131
import static org.junit.Assert.*;
32+
33+
import org.easymock.EasyMock;
3234
import org.junit.Test;
3335
import test.beans.GenericBean;
3436
import test.beans.GenericIntegerBean;
@@ -46,6 +48,7 @@
4648
/**
4749
* @author Juergen Hoeller
4850
* @author Chris Beams
51+
* @author Sam Brannen
4952
* @since 20.01.2006
5053
*/
5154
public class BeanFactoryGenericsTests {
@@ -619,6 +622,30 @@ public void testSetBean() throws Exception {
619622
assertEquals(new URL("http://www.springframework.org"), us.iterator().next());
620623
}
621624

625+
/**
626+
* Tests support for parameterized {@code factory-method} declarations such
627+
* as EasyMock's {@code createMock()} method which has the following signature.
628+
*
629+
* <pre>{@code
630+
* public static <T> T createMock(Class<T> toMock)
631+
* }</pre>
632+
*
633+
* @since 3.2
634+
* @see SPR-9493
635+
*/
636+
@Test
637+
public void parameterizedFactoryMethod() {
638+
RootBeanDefinition rbd = new RootBeanDefinition(EasyMock.class);
639+
rbd.setFactoryMethodName("createMock");
640+
rbd.getConstructorArgumentValues().addGenericArgumentValue(Runnable.class);
641+
642+
DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
643+
bf.registerBeanDefinition("easyMock", rbd);
644+
645+
Map<String, Runnable> beans = bf.getBeansOfType(Runnable.class);
646+
assertEquals(1, beans.size());
647+
}
648+
622649

623650
@SuppressWarnings("serial")
624651
public static class NamedUrlList extends LinkedList<URL> {

spring-beans/src/test/java/org/springframework/beans/factory/xml/FactoryMethodTests.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@
2828
import org.springframework.beans.factory.BeanCreationException;
2929
import org.springframework.beans.factory.BeanDefinitionStoreException;
3030
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
31-
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
3231
import org.springframework.core.io.ClassPathResource;
3332

3433
/**

spring-beans/src/test/resources/log4j.xml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@
1919
<level value="debug" />
2020
</logger>
2121

22+
<logger name="org.springframework.core.GenericTypeResolver">
23+
<level value="warn" />
24+
</logger>
25+
2226
<!-- Root Logger -->
2327
<root>
2428
<priority value="warn" />

spring-core/src/main/java/org/springframework/core/GenericTypeResolver.java

Lines changed: 142 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2002-2011 the original author or authors.
2+
* Copyright 2002-2012 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -30,7 +30,11 @@
3030
import java.util.Map;
3131
import java.util.WeakHashMap;
3232

33+
import org.apache.commons.logging.Log;
34+
import org.apache.commons.logging.LogFactory;
35+
3336
import org.springframework.util.Assert;
37+
import org.springframework.util.ObjectUtils;
3438

3539
/**
3640
* Helper class for resolving generic types against type variables.
@@ -40,11 +44,14 @@
4044
*
4145
* @author Juergen Hoeller
4246
* @author Rob Harrop
47+
* @author Sam Brannen
4348
* @since 2.5.2
4449
* @see GenericCollectionTypeResolver
4550
*/
4651
public abstract class GenericTypeResolver {
4752

53+
private static final Log logger = LogFactory.getLog(GenericTypeResolver.class);
54+
4855
/** Cache from Class to TypeVariable Map */
4956
private static final Map<Class, Reference<Map<TypeVariable, Type>>> typeVariableCache =
5057
Collections.synchronizedMap(new WeakHashMap<Class, Reference<Map<TypeVariable, Type>>>());
@@ -88,18 +95,144 @@ public static Class<?> resolveParameterType(MethodParameter methodParam, Class c
8895
}
8996

9097
/**
91-
* Determine the target type for the generic return type of the given method.
98+
* Determine the target type for the generic return type of the given method,
99+
* where the type variable is declared on the given class.
100+
*
92101
* @param method the method to introspect
93102
* @param clazz the class to resolve type variables against
94103
* @return the corresponding generic parameter or return type
104+
* @see #resolveParameterizedReturnType
95105
*/
96-
public static Class<?> resolveReturnType(Method method, Class clazz) {
106+
public static Class<?> resolveReturnType(Method method, Class<?> clazz) {
97107
Assert.notNull(method, "Method must not be null");
98108
Type genericType = method.getGenericReturnType();
99109
Assert.notNull(clazz, "Class must not be null");
100110
Map<TypeVariable, Type> typeVariableMap = getTypeVariableMap(clazz);
101111
Type rawType = getRawType(genericType, typeVariableMap);
102-
return (rawType instanceof Class ? (Class) rawType : method.getReturnType());
112+
return (rawType instanceof Class ? (Class<?>) rawType : method.getReturnType());
113+
}
114+
115+
/**
116+
* Determine the target type for the generic return type of the given
117+
* <em>parameterized</em> method, where the type variable is declared
118+
* on the given method.
119+
*
120+
* <p>For example, given a factory method with the following signature,
121+
* if {@code resolveParameterizedReturnType()} is invoked with the reflected
122+
* method for {@code creatProxy()} and an {@code Object[]} array containing
123+
* {@code MyService.class}, {@code resolveParameterizedReturnType()} will
124+
* infer that the target return type is {@code MyService}.
125+
*
126+
* <pre>{@code public static <T> T createProxy(Class<T> clazz)}</pre>
127+
*
128+
* <h4>Possible Return Values</h4>
129+
* <ul>
130+
* <li>the target return type if it can be inferred</li>
131+
* <li>the {@link Method#getReturnType() standard return type}, if
132+
* the given {@code method} does not declare any {@link
133+
* Method#getTypeParameters() generic types}</li>
134+
* <li>the {@link Method#getReturnType() standard return type}, if the
135+
* target return type cannot be inferred (e.g., due to type erasure)</li>
136+
* <li>{@code null}, if the length of the given arguments array is shorter
137+
* than the length of the {@link
138+
* Method#getGenericParameterTypes() formal argument list} for the given
139+
* method</li>
140+
* </ul>
141+
*
142+
* @param method the method to introspect, never {@code null}
143+
* @param args the arguments that will be supplied to the method when it is
144+
* invoked, never {@code null}
145+
* @return the resolved target return type, the standard return type, or
146+
* {@code null}
147+
* @since 3.2
148+
* @see #resolveReturnType
149+
*/
150+
public static Class<?> resolveParameterizedReturnType(Method method, Object[] args) {
151+
Assert.notNull(method, "method must not be null");
152+
Assert.notNull(args, "args must not be null");
153+
154+
final TypeVariable<Method>[] declaredGenericTypes = method.getTypeParameters();
155+
final Type genericReturnType = method.getGenericReturnType();
156+
final Type[] genericArgumentTypes = method.getGenericParameterTypes();
157+
158+
if (logger.isDebugEnabled()) {
159+
logger.debug(String.format(
160+
"Resolving parameterized return type for [%s] with concrete method arguments [%s].",
161+
method.toGenericString(), ObjectUtils.nullSafeToString(args)));
162+
}
163+
164+
// No declared generic types to inspect, so just return the standard return type.
165+
if (declaredGenericTypes.length == 0) {
166+
return method.getReturnType();
167+
}
168+
169+
// The supplied argument list is too short for the method's signature, so
170+
// return null, since such a method invocation would fail.
171+
if (args.length < genericArgumentTypes.length) {
172+
return null;
173+
}
174+
175+
// Ensure that the generic type is declared directly on the method
176+
// itself, not on the enclosing class or interface.
177+
boolean locallyDeclaredGenericTypeMatchesReturnType = false;
178+
for (TypeVariable<Method> currentType : declaredGenericTypes) {
179+
if (currentType.equals(genericReturnType)) {
180+
if (logger.isDebugEnabled()) {
181+
logger.debug(String.format(
182+
"Found declared generic type [%s] that matches the target return type [%s].",
183+
currentType, genericReturnType));
184+
}
185+
locallyDeclaredGenericTypeMatchesReturnType = true;
186+
break;
187+
}
188+
}
189+
190+
if (locallyDeclaredGenericTypeMatchesReturnType) {
191+
for (int i = 0; i < genericArgumentTypes.length; i++) {
192+
final Type currentArgumentType = genericArgumentTypes[i];
193+
194+
if (currentArgumentType.equals(genericReturnType)) {
195+
if (logger.isDebugEnabled()) {
196+
logger.debug(String.format(
197+
"Found generic method argument at index [%s] that matches the target return type.", i));
198+
}
199+
return args[i].getClass();
200+
}
201+
202+
if (currentArgumentType instanceof ParameterizedType) {
203+
ParameterizedType parameterizedType = (ParameterizedType) currentArgumentType;
204+
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
205+
206+
for (int j = 0; j < actualTypeArguments.length; j++) {
207+
final Type typeArg = actualTypeArguments[j];
208+
209+
if (typeArg.equals(genericReturnType)) {
210+
if (logger.isDebugEnabled()) {
211+
logger.debug(String.format(
212+
"Found method argument at index [%s] that is parameterized with a type that matches the target return type.",
213+
i));
214+
}
215+
216+
if (args[i] instanceof Class) {
217+
return (Class<?>) args[i];
218+
} else {
219+
// Consider adding logic to determine the class of the
220+
// J'th typeArg, if possible.
221+
logger.info(String.format(
222+
"Could not determine the target type for parameterized type [%s] for method [%s].",
223+
typeArg, method.toGenericString()));
224+
225+
// For now, just fall back...
226+
return method.getReturnType();
227+
}
228+
}
229+
}
230+
}
231+
}
232+
}
233+
234+
// Fall back...
235+
return method.getReturnType();
103236
}
104237

105238
/**
@@ -128,7 +261,7 @@ public static Class<?> resolveReturnTypeArgument(Method method, Class<?> generic
128261
return null;
129262
}
130263
}
131-
return GenericTypeResolver.resolveTypeArgument((Class<?>) returnType, genericIfc);
264+
return resolveTypeArgument((Class<?>) returnType, genericIfc);
132265
}
133266

134267
/**
@@ -186,7 +319,7 @@ private static Class[] doResolveTypeArguments(Class ownerClass, Class classToInt
186319
}
187320
return null;
188321
}
189-
322+
190323
private static Class[] doResolveTypeArguments(Class ownerClass, Type ifc, Class genericIfc) {
191324
if (ifc instanceof ParameterizedType) {
192325
ParameterizedType paramIfc = (ParameterizedType) ifc;
@@ -236,7 +369,6 @@ else if (arg instanceof TypeVariable) {
236369
return (arg instanceof Class ? (Class) arg : Object.class);
237370
}
238371

239-
240372
/**
241373
* Resolve the specified generic type against the given TypeVariable map.
242374
* @param genericType the generic type to resolve
@@ -272,9 +404,9 @@ static Type getRawType(Type genericType, Map<TypeVariable, Type> typeVariableMap
272404
}
273405

274406
/**
275-
* Build a mapping of {@link TypeVariable#getName TypeVariable names} to concrete
276-
* {@link Class} for the specified {@link Class}. Searches all super types,
277-
* enclosing types and interfaces.
407+
* Build a mapping of {@link TypeVariable#getName TypeVariable names} to
408+
* {@link Class concrete classes} for the specified {@link Class}. Searches
409+
* all super types, enclosing types and interfaces.
278410
*/
279411
public static Map<TypeVariable, Type> getTypeVariableMap(Class clazz) {
280412
Reference<Map<TypeVariable, Type>> ref = typeVariableCache.get(clazz);

0 commit comments

Comments
 (0)