SpringMVC 之类型转换Converter 源代码分析

  • 最近研究SpringMVC的类型转换器,在以往我们需要 SpringMVC 为我们自动进行类型转换的时候都是用的PropertyEditor 。通过 PropertyEditor 的 setAsText() 方法我们可以实现字符串向特定类型的转换。但是这里有一个限制是它只支持从 String 类型转为其他类型。在Spring3中 引入了Converter<S, T>接口, 它支持从一个 Object 转为另一个 Object 。除了 Converter接口之外,实现 ConverterFactory 接口和 GenericConverter 接口也可以实现我们自己的类型转换逻辑。
  • 我们先来看一下Converter<S, T>接口的定义
    1. public interface Converter<S, T> {
    2.  
    3. T convert(S source);
    4.  
    5. }
  • S为源对象 T为目标对象 实现该接口即可实现我们的类型转换,我们写一个最为常见的时间类型转换器
    1. public class StringToDateConvert implements Converter<String, Date> {
    2.  
    3. private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    4.  
    5. @Override
    6. public Date convert(String source) {
    7. if(source.length() == 0) {
    8. return null;
    9. }
    10. try {
    11. return format.parse(source);
    12. } catch (ParseException e) {
    13. throw new RuntimeException(source + "类型转换失败");
    14. }
    15. }
    16.  
    17. }
  • 在定义好 Converter 之后,就是使用 Converter 了。为了统一调用 Converter 进行类型转换, Spring 为我们提供了一个 ConversionService 接口。通过实现这个接口我们可以实现自己的 Converter 调用逻辑。我们先来看一下 ConversionService 接口的定义:
    1. public interface ConversionService {
    2.  
    3. boolean canConvert(Class<?> sourceType, Class<?> targetType);
    4. boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType);
    5.  
    6. <T> T convert(Object source, Class<T> targetType);
    7.  
    8. Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType);
    9. }

    我们可以看到 ConversionService 接口里面定义了两个 canConvert 方法和两个convert 方法, canConvert 方法用于判断当前的 ConversionService 是否能够对原类型和目标类型进行转换, convert 方法则是用于进行类型转换的。上面出现的参数类型TypeDescriptor 是对于一种类型的封装,里面包含该种类型的值、实际类型等等信息。

  • 一般而言我们在实现 ConversionService 接口的时候也会实现 ConverterRegistry 接口。使用 ConverterRegistry 可以使我们对类型转换器做一个统一的注册。ConverterRegistry 接口的定义如下:
    1. public interface ConverterRegistry {
    2.  
    3. void addConverter(Converter<?, ?> converter);
    4.  
    5. void addConverter(GenericConverter converter);
    6.  
    7. void addConverterFactory(ConverterFactory<?, ?> converterFactory);
    8.  
    9. void removeConvertible(Class<?> sourceType, Class<?> targetType);
    10.  
    11. }

    有了这俩个接口以后我们就可以发挥我们自己的设计能力实现里面的逻辑了。不过Spring已经为我们提供了一个实现,这个类就是GenericConversionService

  • 首先我们看一下这个类的定义
    1. public class GenericConversionService implements ConfigurableConversionService {}
  • 可以看到 GenericConversionService 继承至ConfigurableConversionService 接口,那ConfigurableConversionService 又是什么呢,我们在看源码
    1. public interface ConfigurableConversionService extends ConversionService, ConverterRegistry {
    2.  
    3. }

    呵呵 这回清楚了吧,GenericConversionService 就是实现了ConversionService接口与ConverterRegistry接口。完成了我们类型转换器的注册 与 转换逻辑,下面我们将通过源代码来详细分析该实现的逻辑。

  • 在分析源代码之前,让我们在看另外俩个转换器,也就是上面提到的 ConverterFactory 接口和 GenericConverter
  • ConverterFactory接口的定义
    1. public interface ConverterFactory<S, R> {
    2.  
    3. <T extends R> Converter<S, T> getConverter(Class<T> targetType);
    4.  
    5. }

    我们可以看到 ConverterFactory 接口里面就定义了一个产生 Converter 的getConverter 方法,参数是目标类型的 class 。我们可以看到 ConverterFactory 中一共用到了三个泛型, S 、 R 、 T ,其中 S 表示原类型, R 表示目标类型, T 是类型 R 的一个子类。

  • 考虑这样一种情况,我们有一个表示用户状态的枚举类型 UserStatus ,如果要定义一个从 String 转为 UserStatus 的 Converter ,根据之前 Converter 接口的说明,我们的StringToUserStatus 大概是这个样子:

    1. public class StringToUserStatus implements Converter<String, UserStatus> {
    2.  
    3. @Override
    4. public UserStatus convert(String source) {
    5. if (source == null) {
    6. return null;
    7. }
    8. return UserStatus.valueOf(source);
    9. }
    10.  
    11. }

    如果这个时候有另外一个枚举类型 UserType ,那么我们就需要定义另外一个从String 转为 UserType 的 Converter —— StringToUserType ,那么我们的StringToUserType 大概是这个样子:

    1. public class StringToUserType implements Converter<String, UserType> {
    2.  
    3. @Override
    4. public UserType convert(String source) {
    5. if (source == null) {
    6. return null;
    7. }
    8. return UserType.valueOf(source);
    9. }
    10.  
    11. }

    如果还有其他枚举类型需要定义原类型为 String 的 Converter 的时候,我们还得像上面那样定义对应的 Converter 。有了 ConverterFactory 之后,这一切都变得非常简单,因为 UserStatus 、 UserType 等其他枚举类型同属于枚举,所以这个时候我们就可以统一定义一个从 String 到 Enum 的 ConverterFactory ,然后从中获取对应的Converter 进行 convert 操作。 Spring 官方已经为我们实现了这么一个StringToEnumConverterFactory :

    1. @SuppressWarnings("unchecked")
    2. final class StringToEnumConverterFactory implements ConverterFactory<String, Enum> {
    3.  
    4. public <T extends Enum> Converter<String, T> getConverter(Class<T> targetType) {
    5. return new StringToEnum(targetType);
    6. }
    7.  
    8. private class StringToEnum<T extends Enum> implements Converter<String, T> {
    9.  
    10. private final Class<T> enumType;
    11.  
    12. public StringToEnum(Class<T> enumType) {
    13. this.enumType = enumType;
    14. }
    15.  
    16. public T convert(String source) {
    17. if (source.length() == 0) {
    18. // It's an empty enum identifier: reset the enum value to null.
    19. return null;
    20. }
    21. return (T) Enum.valueOf(this.enumType, source.trim());
    22. }
    23. }
    24.  
    25. }

    这样,如果是要进行 String 到 UserStatus 的转换,我们就可以通过StringToEnumConverterFactory 实例的 getConverter(UserStatus.class).convert(string)获取到对应的 UserStatus ,如果是要转换为 UserType 的话就是getConverter(UserType.class).convert(string) 。这样就非常方便,可以很好的支持扩展。

  • 看GenericConverter 接口的定义
  • GenericConverter 接口是所有的 Converter 接口中最灵活也是最复杂的一个类型转换接口。像我们之前介绍的 Converter 接口只支持从一个原类型转换为一个目标类型;ConverterFactory 接口只支持从一个原类型转换为一个目标类型对应的子类型;而GenericConverter 接口支持在多个不同的原类型和目标类型之间进行转换,这也就是GenericConverter 接口灵活和复杂的地方。
  • 我们先来看一下 GenericConverter 接口的定义:
    1. public interface GenericConverter {
    2.  
    3. Set<ConvertiblePair> getConvertibleTypes();
    4.  
    5. Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType);
    6.  
    7. public static final class ConvertiblePair {
    8.  
    9. private final Class<?> sourceType;
    10.  
    11. private final Class<?> targetType;
    12.  
    13. public ConvertiblePair(Class<?> sourceType, Class<?> targetType) {
    14. Assert.notNull(sourceType, "Source type must not be null");
    15. Assert.notNull(targetType, "Target type must not be null");
    16. this.sourceType = sourceType;
    17. this.targetType = targetType;
    18. }
    19.  
    20. public Class<?> getSourceType() {
    21. return this.sourceType;
    22. }
    23.  
    24. public Class<?> getTargetType() {
    25. return this.targetType;
    26. }
    27. }
    28.  
    29. }

    我们可以看到 GenericConverter 接口中一共定义了两个方法,getConvertibleTypes() 和 convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) 。 getConvertibleTypes 方法用于返回这个GenericConverter 能够转换的原类型和目标类型的这么一个组合; convert 方法则是用于进行类型转换的,我们可以在这个方法里面实现我们自己的转换逻辑。之所以说GenericConverter 是最复杂的是因为它的转换方法 convert 的参数类型 TypeDescriptor是比较复杂的。 TypeDescriptor 对类型 Type 进行了一些封装,包括 value 、 Field 及其对应的真实类型等等,具体的可以查看 API 。

有了上面的基础以后就让我们一起来分析一下Spring为我们提供的GenericConversionService这个类

  1. /**
  2. * Spring GenericConversionService 类型转换器核心源代码分析
  3. */
  4. public class GenericConversionService implements ConfigurableConversionService {
  5.  
  6. //这个转换器在没有找到对应转化器 并且 源类型与目标类型是同一种类型时使用
  7. private static final GenericConverter NO_OP_CONVERTER = new GenericConverter() {
  8. public Set<ConvertiblePair> getConvertibleTypes() {
  9. return null;
  10. }
  11. public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
  12. //可以看到这里并没有做处理,直接将原类型返回
  13. return source;
  14. }
  15. public String toString() {
  16. return "NO_OP";
  17. }
  18. };
  19.  
  20. //这个转换器在没有找到对应转化器 并且 源类型与目标类型不是同一种类型时使用。将抛出异常
  21. private static final GenericConverter NO_MATCH = new GenericConverter() {
  22. public Set<ConvertiblePair> getConvertibleTypes() {
  23. throw new UnsupportedOperationException();
  24. }
  25. public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
  26. throw new UnsupportedOperationException();
  27. }
  28. public String toString() {
  29. return "NO_MATCH";
  30. }
  31. };
  32.  
  33. // converters存放系统所有的类型转换器
  34. // 其结构为 key = sourceType ; value = Map<Class<?>, MatchableConverters>;
  35. // 至于MatchableConverters是什么 在后面会讲到
  36. // 整个converters的数据接口大概是这样的
  37. /**
  38. * 一个原类型对应一个Map<targetType<?>, MatchableConverters>数据结构
  39. * converters
  40. * [key: String value = Map<targetType<?>, MatchableConverters>]
  41. * [key: sourceType1 value = Map<targetType<?>, MatchableConverters>]
  42. * [key: sourceType2 value = Map<targetType<?>, MatchableConverters>]
  43. *
  44. *
  45. *
  46. * 一个Map<targetType<?>, MatchableConverters>数据结构包含每种目标类型对应的转换器
  47. * Map<targetType<?>, MatchableConverters>
  48. * [key:int value=MatchableConverters]
  49. * [key:targetType1 value=MatchableConverters(1)]
  50. * [key:targetType2 value=MatchableConverters(2)]
  51. *
  52. */
  53. private final Map<Class<?>, Map<Class<?>, MatchableConverters>> converters =
  54. new HashMap<Class<?>, Map<Class<?>, MatchableConverters>>(36);
  55.  
  56. // 转换器缓存
  57. // 系统在对某个类型第一次做转换的时候会先去查找匹配的转换器,找到以后会放到这个数据结构之中 提高效率
  58. private final Map<ConverterCacheKey, GenericConverter> converterCache =
  59. new ConcurrentHashMap<ConverterCacheKey, GenericConverter>();
  60.  
  61. //注册类型转换器 Converter接口 这个接口就是像我们上面例子里提到的StringToDateConvert
  62. public void addConverter(Converter<?, ?> converter) {
  63. //首先根据converter的实例 获取原类型(sourceType) 与 目标类型(targetType)的对象
  64. //关于GenericConverter.ConvertiblePair类 就是对 原类型与目标类型的一种封装
  65. GenericConverter.ConvertiblePair typeInfo = getRequiredTypeInfo(converter, Converter.class);
  66. if (typeInfo == null) {
  67. throw new IllegalArgumentException("Unable to the determine sourceType <S> and targetType <T> which " +
  68. "your Converter<S, T> converts between; declare these generic types.");
  69. }
  70. //注册转换器
  71. //关于ConverterAdapter的解释 在该类上面有详细的解释
  72. addConverter(new ConverterAdapter(typeInfo, converter));
  73. }
  74.  
  75. public void addConverter(Class<?> sourceType, Class<?> targetType, Converter<?, ?> converter) {
  76. GenericConverter.ConvertiblePair typeInfo = new GenericConverter.ConvertiblePair(sourceType, targetType);
  77. addConverter(new ConverterAdapter(typeInfo, converter));
  78. }
  79.  
  80. //最终所有的转换器 ConverterFactory,Converter,ConditionalGenericConverter 都会被转换为GenericConverter
  81. //对象进行注册 也就是说 GenericConversionService类里的转换器 最终都被包装为GenericConverter对象
  82. public void addConverter(GenericConverter converter) {
  83. //拿到GenericConverter所支持的转换类型(GenericConverter.ConvertiblePair)的集合
  84. Set<GenericConverter.ConvertiblePair> convertibleTypes = converter.getConvertibleTypes();
  85. //循环拿出没一种 转换类型组合进行注册
  86. for (GenericConverter.ConvertiblePair convertibleType : convertibleTypes) {
  87. //将converter对象添加到MatchableConverters对象当中去
  88. getMatchableConverters(convertibleType.getSourceType(), convertibleType.getTargetType()).add(converter);
  89. }
  90. invalidateCache();
  91. }
  92.  
  93. //注册实现ConverterFactory<?, ?>接口的转换器
  94. //该方法还是将ConverterFactory的实现类包装为GenericConverter对象
  95. public void addConverterFactory(ConverterFactory<?, ?> converterFactory) {
  96. GenericConverter.ConvertiblePair typeInfo = getRequiredTypeInfo(converterFactory, ConverterFactory.class);
  97. if (typeInfo == null) {
  98. throw new IllegalArgumentException("Unable to the determine sourceType <S> and targetRangeType R which " +
  99. "your ConverterFactory<S, R> converts between; declare these generic types.");
  100. }
  101. addConverter(new ConverterFactoryAdapter(typeInfo, converterFactory));
  102. }
  103.  
  104. //移除某种类型的转换器
  105. public void removeConvertible(Class<?> sourceType, Class<?> targetType) {
  106. getSourceConverterMap(sourceType).remove(targetType);
  107. invalidateCache();
  108. }
  109.  
  110. //判断是否能够转换
  111. public boolean canConvert(Class<?> sourceType, Class<?> targetType) {
  112. if (targetType == null) {
  113. throw new IllegalArgumentException("The targetType to convert to cannot be null");
  114. }
  115. return canConvert(sourceType != null ? TypeDescriptor.valueOf(sourceType) : null, TypeDescriptor.valueOf(targetType));
  116. }
  117.  
  118. //判断是否能够转换
  119. public boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType) {
  120. if (targetType == null) {
  121. throw new IllegalArgumentException("The targetType to convert to cannot be null");
  122. }
  123. if (sourceType == null) {
  124. return true;
  125. }
  126. GenericConverter converter = getConverter(sourceType, targetType);
  127. return (converter != null);
  128. }
  129.  
  130. @SuppressWarnings("unchecked")
  131. public <T> T convert(Object source, Class<T> targetType) {
  132. if (targetType == null) {
  133. throw new IllegalArgumentException("The targetType to convert to cannot be null");
  134. }
  135. return (T) convert(source, TypeDescriptor.forObject(source), TypeDescriptor.valueOf(targetType));
  136. }
  137.  
  138. public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
  139. if (targetType == null) {
  140. throw new IllegalArgumentException("The targetType to convert to cannot be null");
  141. }
  142. if (sourceType == null) {
  143. Assert.isTrue(source == null, "The source must be [null] if sourceType == [null]");
  144. return handleResult(sourceType, targetType, convertNullSource(sourceType, targetType));
  145. }
  146. if (source != null && !sourceType.getObjectType().isInstance(source)) {
  147. throw new IllegalArgumentException("The source to convert from must be an instance of " +
  148. sourceType + "; instead it was a " + source.getClass().getName());
  149. }
  150. GenericConverter converter = getConverter(sourceType, targetType);
  151. if (converter != null) {
  152. Object result = ConversionUtils.invokeConverter(converter, source, sourceType, targetType);
  153. return handleResult(sourceType, targetType, result);
  154. }
  155. else {
  156. return handleConverterNotFound(source, sourceType, targetType);
  157. }
  158. }
  159.  
  160. /**
  161. * Convenience operation for converting a source object to the specified targetType, where the targetType is a descriptor that provides additional conversion context.
  162. * Simply delegates to {@link #convert(Object, TypeDescriptor, TypeDescriptor)} and encapsulates the construction of the sourceType descriptor using {@link TypeDescriptor#forObject(Object)}.
  163. * @param source the source object
  164. * @param targetType the target type
  165. * @return the converted value
  166. * @throws ConversionException if a conversion exception occurred
  167. * @throws IllegalArgumentException if targetType is null
  168. * @throws IllegalArgumentException if sourceType is null but source is not null
  169. */
  170. public Object convert(Object source, TypeDescriptor targetType) {
  171. return convert(source, TypeDescriptor.forObject(source), targetType);
  172. }
  173.  
  174. public String toString() {
  175. List<String> converterStrings = new ArrayList<String>();
  176. for (Map<Class<?>, MatchableConverters> targetConverters : this.converters.values()) {
  177. for (MatchableConverters matchable : targetConverters.values()) {
  178. converterStrings.add(matchable.toString());
  179. }
  180. }
  181. Collections.sort(converterStrings);
  182. StringBuilder builder = new StringBuilder();
  183. builder.append("ConversionService converters = ").append("\n");
  184. for (String converterString : converterStrings) {
  185. builder.append("\t");
  186. builder.append(converterString);
  187. builder.append("\n");
  188. }
  189. return builder.toString();
  190. }
  191.  
  192. // subclassing hooks
  193.  
  194. /**
  195. * Template method to convert a null source.
  196. * <p>Default implementation returns <code>null</code>.
  197. * Subclasses may override to return custom null objects for specific target types.
  198. * @param sourceType the sourceType to convert from
  199. * @param targetType the targetType to convert to
  200. * @return the converted null object
  201. */
  202. protected Object convertNullSource(TypeDescriptor sourceType, TypeDescriptor targetType) {
  203. return null;
  204. }
  205.  
  206. /**
  207. * Hook method to lookup the converter for a given sourceType/targetType pair.
  208. * First queries this ConversionService's converter cache.
  209. * On a cache miss, then performs an exhaustive search for a matching converter.
  210. * If no converter matches, returns the default converter.
  211. * Subclasses may override.
  212. * @param sourceType the source type to convert from
  213. * @param targetType the target type to convert to
  214. * @return the generic converter that will perform the conversion, or <code>null</code> if no suitable converter was found
  215. * @see #getDefaultConverter(TypeDescriptor, TypeDescriptor)
  216. */
  217. protected GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
  218. ConverterCacheKey key = new ConverterCacheKey(sourceType, targetType);
  219. GenericConverter converter = this.converterCache.get(key);
  220. if (converter != null) {
  221. return (converter != NO_MATCH ? converter : null);
  222. }
  223. else {
  224. converter = findConverterForClassPair(sourceType, targetType);
  225. if (converter == null) {
  226. converter = getDefaultConverter(sourceType, targetType);
  227. }
  228. if (converter != null) {
  229. this.converterCache.put(key, converter);
  230. return converter;
  231. }
  232. else {
  233. this.converterCache.put(key, NO_MATCH);
  234. return null;
  235. }
  236. }
  237. }
  238.  
  239. /**
  240. * Return the default converter if no converter is found for the given sourceType/targetType pair.
  241. * Returns a NO_OP Converter if the sourceType is assignable to the targetType.
  242. * Returns <code>null</code> otherwise, indicating no suitable converter could be found.
  243. * Subclasses may override.
  244. * @param sourceType the source type to convert from
  245. * @param targetType the target type to convert to
  246. * @return the default generic converter that will perform the conversion
  247. */
  248. protected GenericConverter getDefaultConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
  249. return (sourceType.isAssignableTo(targetType) ? NO_OP_CONVERTER : null);
  250. }
  251.  
  252. //通过反射的到Converter<S, T>接口的 S与T 封装成GenericConverter.ConvertiblePair对象返回
  253. private GenericConverter.ConvertiblePair getRequiredTypeInfo(Object converter, Class<?> genericIfc) {
  254. Class<?>[] args = GenericTypeResolver.resolveTypeArguments(converter.getClass(), genericIfc);
  255. return (args != null ? new GenericConverter.ConvertiblePair(args[0], args[1]) : null);
  256. }
  257.  
  258. private MatchableConverters getMatchableConverters(Class<?> sourceType, Class<?> targetType) {
  259. //通过sourceType(原类型)在converters当中获取Map<Class<?>, MatchableConverters>对象
  260. Map<Class<?>, MatchableConverters> sourceMap = getSourceConverterMap(sourceType);
  261.  
  262. //在Map<Class<?>, MatchableConverters>对象当中根据targetType(目标类型)获取MatchableConverters对象
  263. MatchableConverters matchable = sourceMap.get(targetType);
  264. if (matchable == null) {
  265. matchable = new MatchableConverters();
  266. sourceMap.put(targetType, matchable);
  267. }
  268. return matchable;
  269. }
  270.  
  271. private void invalidateCache() {
  272. this.converterCache.clear();
  273. }
  274.  
  275. //通过sourceType(原类型)在converters当中获取Map<Class<?>, MatchableConverters>
  276. private Map<Class<?>, MatchableConverters> getSourceConverterMap(Class<?> sourceType) {
  277. Map<Class<?>, MatchableConverters> sourceMap = converters.get(sourceType);
  278. //为null就创建一个
  279. if (sourceMap == null) {
  280. sourceMap = new HashMap<Class<?>, MatchableConverters>();
  281. this.converters.put(sourceType, sourceMap);
  282. }
  283. return sourceMap;
  284. }
  285.  
  286. private GenericConverter findConverterForClassPair(TypeDescriptor sourceType, TypeDescriptor targetType) {
  287. Class<?> sourceObjectType = sourceType.getObjectType();
  288. if (sourceObjectType.isInterface()) {
  289. LinkedList<Class<?>> classQueue = new LinkedList<Class<?>>();
  290. classQueue.addFirst(sourceObjectType);
  291. while (!classQueue.isEmpty()) {
  292. Class<?> currentClass = classQueue.removeLast();
  293. Map<Class<?>, MatchableConverters> converters = getTargetConvertersForSource(currentClass);
  294. GenericConverter converter = getMatchingConverterForTarget(sourceType, targetType, converters);
  295. if (converter != null) {
  296. return converter;
  297. }
  298. Class<?>[] interfaces = currentClass.getInterfaces();
  299. for (Class<?> ifc : interfaces) {
  300. classQueue.addFirst(ifc);
  301. }
  302. }
  303. Map<Class<?>, MatchableConverters> objectConverters = getTargetConvertersForSource(Object.class);
  304. return getMatchingConverterForTarget(sourceType, targetType, objectConverters);
  305. }
  306. else if (sourceObjectType.isArray()) {
  307. LinkedList<Class<?>> classQueue = new LinkedList<Class<?>>();
  308. classQueue.addFirst(sourceObjectType);
  309. while (!classQueue.isEmpty()) {
  310. Class<?> currentClass = classQueue.removeLast();
  311. Map<Class<?>, MatchableConverters> converters = getTargetConvertersForSource(currentClass);
  312. GenericConverter converter = getMatchingConverterForTarget(sourceType, targetType, converters);
  313. if (converter != null) {
  314. return converter;
  315. }
  316. Class<?> componentType = ClassUtils.resolvePrimitiveIfNecessary(currentClass.getComponentType());
  317. if (componentType.getSuperclass() != null) {
  318. classQueue.addFirst(Array.newInstance(componentType.getSuperclass(), 0).getClass());
  319. }
  320. else if (componentType.isInterface()) {
  321. classQueue.addFirst(Object[].class);
  322. }
  323. }
  324. return null;
  325. }
  326. else {
  327. HashSet<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
  328. LinkedList<Class<?>> classQueue = new LinkedList<Class<?>>();
  329. classQueue.addFirst(sourceObjectType);
  330. while (!classQueue.isEmpty()) {
  331. Class<?> currentClass = classQueue.removeLast();
  332. Map<Class<?>, MatchableConverters> converters = getTargetConvertersForSource(currentClass);
  333. GenericConverter converter = getMatchingConverterForTarget(sourceType, targetType, converters);
  334. if (converter != null) {
  335. return converter;
  336. }
  337. Class<?> superClass = currentClass.getSuperclass();
  338. if (superClass != null && superClass != Object.class) {
  339. classQueue.addFirst(superClass);
  340. }
  341. for (Class<?> interfaceType : currentClass.getInterfaces()) {
  342. addInterfaceHierarchy(interfaceType, interfaces);
  343. }
  344. }
  345. for (Class<?> interfaceType : interfaces) {
  346. Map<Class<?>, MatchableConverters> converters = getTargetConvertersForSource(interfaceType);
  347. GenericConverter converter = getMatchingConverterForTarget(sourceType, targetType, converters);
  348. if (converter != null) {
  349. return converter;
  350. }
  351. }
  352. Map<Class<?>, MatchableConverters> objectConverters = getTargetConvertersForSource(Object.class);
  353. return getMatchingConverterForTarget(sourceType, targetType, objectConverters);
  354. }
  355. }
  356.  
  357. private Map<Class<?>, MatchableConverters> getTargetConvertersForSource(Class<?> sourceType) {
  358. Map<Class<?>, MatchableConverters> converters = this.converters.get(sourceType);
  359. if (converters == null) {
  360. converters = Collections.emptyMap();
  361. }
  362. return converters;
  363. }
  364.  
  365. private GenericConverter getMatchingConverterForTarget(TypeDescriptor sourceType, TypeDescriptor targetType,
  366. Map<Class<?>, MatchableConverters> converters) {
  367. Class<?> targetObjectType = targetType.getObjectType();
  368. if (targetObjectType.isInterface()) {
  369. LinkedList<Class<?>> classQueue = new LinkedList<Class<?>>();
  370. classQueue.addFirst(targetObjectType);
  371. while (!classQueue.isEmpty()) {
  372. Class<?> currentClass = classQueue.removeLast();
  373. MatchableConverters matchable = converters.get(currentClass);
  374. GenericConverter converter = matchConverter(matchable, sourceType, targetType);
  375. if (converter != null) {
  376. return converter;
  377. }
  378. Class<?>[] interfaces = currentClass.getInterfaces();
  379. for (Class<?> ifc : interfaces) {
  380. classQueue.addFirst(ifc);
  381. }
  382. }
  383. return matchConverter(converters.get(Object.class), sourceType, targetType);
  384. }
  385. else if (targetObjectType.isArray()) {
  386. LinkedList<Class<?>> classQueue = new LinkedList<Class<?>>();
  387. classQueue.addFirst(targetObjectType);
  388. while (!classQueue.isEmpty()) {
  389. Class<?> currentClass = classQueue.removeLast();
  390. MatchableConverters matchable = converters.get(currentClass);
  391. GenericConverter converter = matchConverter(matchable, sourceType, targetType);
  392. if (converter != null) {
  393. return converter;
  394. }
  395. Class<?> componentType = ClassUtils.resolvePrimitiveIfNecessary(currentClass.getComponentType());
  396. if (componentType.getSuperclass() != null) {
  397. classQueue.addFirst(Array.newInstance(componentType.getSuperclass(), 0).getClass());
  398. }
  399. else if (componentType.isInterface()) {
  400. classQueue.addFirst(Object[].class);
  401. }
  402. }
  403. return null;
  404. }
  405. else {
  406. Set<Class<?>> interfaces = new LinkedHashSet<Class<?>>();
  407. LinkedList<Class<?>> classQueue = new LinkedList<Class<?>>();
  408. classQueue.addFirst(targetObjectType);
  409. while (!classQueue.isEmpty()) {
  410. Class<?> currentClass = classQueue.removeLast();
  411. MatchableConverters matchable = converters.get(currentClass);
  412. GenericConverter converter = matchConverter(matchable, sourceType, targetType);
  413. if (converter != null) {
  414. return converter;
  415. }
  416. Class<?> superClass = currentClass.getSuperclass();
  417. if (superClass != null && superClass != Object.class) {
  418. classQueue.addFirst(superClass);
  419. }
  420. for (Class<?> interfaceType : currentClass.getInterfaces()) {
  421. addInterfaceHierarchy(interfaceType, interfaces);
  422. }
  423. }
  424. for (Class<?> interfaceType : interfaces) {
  425. MatchableConverters matchable = converters.get(interfaceType);
  426. GenericConverter converter = matchConverter(matchable, sourceType, targetType);
  427. if (converter != null) {
  428. return converter;
  429. }
  430. }
  431. return matchConverter(converters.get(Object.class), sourceType, targetType);
  432. }
  433. }
  434.  
  435. private void addInterfaceHierarchy(Class<?> interfaceType, Set<Class<?>> interfaces) {
  436. interfaces.add(interfaceType);
  437. for (Class<?> inheritedInterface : interfaceType.getInterfaces()) {
  438. addInterfaceHierarchy(inheritedInterface, interfaces);
  439. }
  440. }
  441.  
  442. private GenericConverter matchConverter(
  443. MatchableConverters matchable, TypeDescriptor sourceFieldType, TypeDescriptor targetFieldType) {
  444. if (matchable == null) {
  445. return null;
  446. }
  447. return matchable.matchConverter(sourceFieldType, targetFieldType);
  448. }
  449.  
  450. private Object handleConverterNotFound(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
  451. if (source == null) {
  452. assertNotPrimitiveTargetType(sourceType, targetType);
  453. return source;
  454. }
  455. else if (sourceType.isAssignableTo(targetType) && targetType.getObjectType().isInstance(source)) {
  456. return source;
  457. }
  458. else {
  459. throw new ConverterNotFoundException(sourceType, targetType);
  460. }
  461. }
  462.  
  463. private Object handleResult(TypeDescriptor sourceType, TypeDescriptor targetType, Object result) {
  464. if (result == null) {
  465. assertNotPrimitiveTargetType(sourceType, targetType);
  466. }
  467. return result;
  468. }
  469. private void assertNotPrimitiveTargetType(TypeDescriptor sourceType, TypeDescriptor targetType) {
  470. if (targetType.isPrimitive()) {
  471. throw new ConversionFailedException(sourceType, targetType, null,
  472. new IllegalArgumentException("A null value cannot be assigned to a primitive type"));
  473. }
  474. }
  475.  
  476. //包装我们的Converter类 将我们的Converter类的实例 包装成为GenericConverter对象 以便统一注册
  477. @SuppressWarnings("unchecked")
  478. private final class ConverterAdapter implements GenericConverter {
  479.  
  480. //原类型(sourceType) 与 目标类型(targetType)
  481. private final ConvertiblePair typeInfo;
  482.  
  483. //我们实现Converter<S,T>接口的转换器
  484. private final Converter<Object, Object> converter;
  485.  
  486. //构造函数
  487. public ConverterAdapter(ConvertiblePair typeInfo, Converter<?, ?> converter) {
  488. this.converter = (Converter<Object, Object>) converter;
  489. this.typeInfo = typeInfo;
  490. }
  491.  
  492. //返回一个Set 里面包含了当前ConverterAdapter对象能够转换的类型信息
  493. public Set<ConvertiblePair> getConvertibleTypes() {
  494. return Collections.singleton(this.typeInfo);
  495. }
  496.  
  497. public boolean matchesTargetType(TypeDescriptor targetType) {
  498. return this.typeInfo.getTargetType().equals(targetType.getObjectType());
  499. }
  500.  
  501. //具体转换逻辑
  502. public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
  503. if (source == null) {
  504. return convertNullSource(sourceType, targetType);
  505. }
  506. //拿到实现Converter<S,T>接口的转换器进行转换
  507. return this.converter.convert(source);
  508. }
  509.  
  510. public String toString() {
  511. return this.typeInfo.getSourceType().getName() + " -> " + this.typeInfo.getTargetType().getName() +
  512. " : " + this.converter.toString();
  513. }
  514. }
  515.  
  516. //包装我们的Converter类 将我们的ConverterFactory类的实例 包装成为GenericConverter对象 以便统一注册
  517. @SuppressWarnings("unchecked")
  518. private final class ConverterFactoryAdapter implements GenericConverter {
  519.  
  520. //原类型(sourceType) 与 目标类型(targetType)
  521. private final ConvertiblePair typeInfo;
  522.  
  523. //实现了ConverterFactory接口的类对象
  524. private final ConverterFactory<Object, Object> converterFactory;
  525.  
  526. public ConverterFactoryAdapter(ConvertiblePair typeInfo, ConverterFactory<?, ?> converterFactory) {
  527. this.converterFactory = (ConverterFactory<Object, Object>) converterFactory;
  528. this.typeInfo = typeInfo;
  529. }
  530.  
  531. //返回一个Set 里面包含了当前ConverterAdapter对象能够转换的类型信息
  532. public Set<ConvertiblePair> getConvertibleTypes() {
  533. return Collections.singleton(this.typeInfo);
  534. }
  535.  
  536. //转换逻辑
  537. public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
  538. if (source == null) {
  539. return convertNullSource(sourceType, targetType);
  540. }
  541. //通过ConverterFactory的getConverter拿到转换器对象在进行转换
  542. return this.converterFactory.getConverter(targetType.getObjectType()).convert(source);
  543. }
  544.  
  545. public String toString() {
  546. return this.typeInfo.getSourceType().getName() + " -> " + this.typeInfo.getTargetType().getName() +
  547. " : " + this.converterFactory.toString();
  548. }
  549. }
  550.  
  551. private static class MatchableConverters {
  552.  
  553. //支持条件的转换器
  554. private LinkedList<ConditionalGenericConverter> conditionalConverters;
  555.  
  556. //默认转换器
  557. private GenericConverter defaultConverter;
  558.  
  559. public void add(GenericConverter converter) {
  560. if (converter instanceof ConditionalGenericConverter) {
  561. if (this.conditionalConverters == null) {
  562. this.conditionalConverters = new LinkedList<ConditionalGenericConverter>();
  563. }
  564. this.conditionalConverters.addFirst((ConditionalGenericConverter) converter);
  565. }
  566. else {
  567. this.defaultConverter = converter;
  568. }
  569. }
  570.  
  571. //匹配转换器
  572. public GenericConverter matchConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
  573. //如果conditionalConverters转换器不为空 那么优先查找
  574. if (this.conditionalConverters != null) {
  575. for (ConditionalGenericConverter conditional : this.conditionalConverters) {
  576. //通过matches方法进行匹配 如果匹配到了则返回该转换器
  577. if (conditional.matches(sourceType, targetType)) {
  578. return conditional;
  579. }
  580. }
  581. }
  582. //判断是不是ConverterAdapter 如果是这调用matchesTargetType方法看是否能够转换
  583. if (this.defaultConverter instanceof ConverterAdapter) {
  584. ConverterAdapter adapter = (ConverterAdapter) this.defaultConverter;
  585. if (!adapter.matchesTargetType(targetType)) {
  586. return null;
  587. }
  588. }
  589. //返回转换器
  590. return this.defaultConverter;
  591. }
  592.  
  593. public String toString() {
  594. if (this.conditionalConverters != null) {
  595. StringBuilder builder = new StringBuilder();
  596. for (Iterator<ConditionalGenericConverter> it = this.conditionalConverters.iterator(); it.hasNext();) {
  597. builder.append(it.next());
  598. if (it.hasNext()) {
  599. builder.append(", ");
  600. }
  601. }
  602. if (this.defaultConverter != null) {
  603. builder.append(", ").append(this.defaultConverter);
  604. }
  605. return builder.toString();
  606. }
  607. else {
  608. return this.defaultConverter.toString();
  609. }
  610. }
  611. }
  612.  
  613. private static final class ConverterCacheKey {
  614.  
  615. private final TypeDescriptor sourceType;
  616.  
  617. private final TypeDescriptor targetType;
  618.  
  619. public ConverterCacheKey(TypeDescriptor sourceType, TypeDescriptor targetType) {
  620. this.sourceType = sourceType;
  621. this.targetType = targetType;
  622. }
  623.  
  624. public boolean equals(Object other) {
  625. if (this == other) {
  626. return true;
  627. }
  628. if (!(other instanceof ConverterCacheKey)) {
  629. return false;
  630. }
  631. ConverterCacheKey otherKey = (ConverterCacheKey) other;
  632. return this.sourceType.equals(otherKey.sourceType) && this.targetType.equals(otherKey.targetType);
  633. }
  634.  
  635. public int hashCode() {
  636. return this.sourceType.hashCode() * 29 + this.targetType.hashCode();
  637. }
  638.  
  639. public String toString() {
  640. return "ConverterCacheKey [sourceType = " + this.sourceType + ", targetType = " + this.targetType + "]";
  641. }
  642. }
  643.  
  644. }

SpringMVC 之类型转换Converter 源代码分析的更多相关文章

  1. 转:SpringMVC之类型转换Converter(GenericConverter)

    转: http://blog.csdn.net/fsp88927/article/details/37692215 SpringMVC 之类型转换 Converter 1.1 目录 1.1 目录 1. ...

  2. SpringMVC 之类型转换Converter详解转载

    SpringMVC之类型转换Converter详解 本文转载 http://www.tuicool.com/articles/uUjaum 1.1     目录 1.1      目录 1.2     ...

  3. SpringMVC之类型转换Converter

    (转载:http://blog.csdn.net/renhui999/article/details/9837897) 1.1     目录 1.1      目录 1.2      前言 1.3   ...

  4. 【Spring学习笔记-MVC-8】SpringMVC之类型转换Converter

    作者:ssslinppp       1. 摘要 在spring 中定义了3中类型转换接口,分别为: Converter接口              :使用最简单,最不灵活: ConverterFa ...

  5. springmvc的类型转换

     一.springmvc的类型转换 (一)默认情况下,springmvc内置的类型转换器只能 将"yyyy/MM/dd"类型的字符串转换为Date类型的日期 情境一: 而现在我们无 ...

  6. android-plugmgr源代码分析

    android-plugmgr是一个Android插件加载框架,它最大的特点就是对插件不需要进行任何约束.关于这个类库的介绍见作者博客,市面上也有一些插件加载框架,但是感觉没有这个好.在这篇文章中,我 ...

  7. Twitter Storm源代码分析之ZooKeeper中的目录结构

    徐明明博客:Twitter Storm源代码分析之ZooKeeper中的目录结构 我们知道Twitter Storm的所有的状态信息都是保存在Zookeeper里面,nimbus通过在zookeepe ...

  8. 转:SDL2源代码分析

    1:初始化(SDL_Init()) SDL简介 有关SDL的简介在<最简单的视音频播放示例7:SDL2播放RGB/YUV>以及<最简单的视音频播放示例9:SDL2播放PCM>中 ...

  9. 转:RTMPDump源代码分析

    0: 主要函数调用分析 rtmpdump 是一个用来处理 RTMP 流媒体的开源工具包,支持 rtmp://, rtmpt://, rtmpe://, rtmpte://, and rtmps://. ...

随机推荐

  1. 给电脑装完系统之后,发现U盘少了几个G!

    我的U盘是8个G的,有一次用U盘给电脑装完系统,过了几天后再次用的时候发现U盘 突然少了几个G,刚开始不知道怎么回事,然后就格式化U盘,但是格式化之后没有任何 变化. 在网上搜了一下,说是U盘有可能被 ...

  2. SQLServer2008备份时发生无法打开备份设备

    如下图所示,在执行SQL一个简单的备份命令时发生下面的情况 问题分析: 1:可能是文件夹目录权限问题 2:可能是登录SQLServer服务器用户策略问题 于是就查看了E:\dw_backup的文件夹权 ...

  3. 关于DrawIndexedPrimitive函数的调用

    函数的原型例如以下所看到的: HRESULT DrawIndexedPrimitive( [in] D3DPRIMITIVETYPE Type, [in] INT BaseVertexIndex, [ ...

  4. APNS 生成证书 p12 或者 PEM

    .net环境下须要p12文件,下面是生成p12过程 1.$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem ...

  5. ASP服务器I I S出现authentication mode=Windows错误解决办法

    网上下载的asp.net源码出现 <authentication mode="Windows"/>错误信息 属性 说明 mode 必选的属性. 指定应用程序的默认身份验 ...

  6. SpriteKit改变Node锚点其物理对象位置不对的解决

    在创建Node的物理对象后,默认情况下物理对象和Node的实际边界相应的非常好,由于此时Node的默认锚点是当中心位置即(0.5,0.5),只是假设我们改变了Node的锚点,就会发现其物理边界还是保持 ...

  7. [Android exception] /data/app/com.tongyan.tutelage-1/lib/arm/libstlport_shared.so: has text relocations

    java.lang.UnsatisfiedLinkError: dlopen failed: /data/app/com.tongyan.tutelage-1/lib/arm/libstlport_s ...

  8. SQL Server Management Studio 简单使用说明

    1.对数据库中的数据生成脚本 a.选中要生成脚本的数据库右键->任务->生成脚本(如下图)->下一步->下一步->选中你想要生成的内容->下一步->完成

  9. 14-spring学习-变量操作

    表达式所有操作都是可以以变量形式出现的. 观察变量的定义: package com.Spring.ELDemo; import org.springframework.expression.Evalu ...

  10. android下载

    1. 源码下载链接: http://source.android.com/source/downloading.html 参考链接: Android源码下载方法详解 2. SDK下载 http://d ...