ObjectToCollectionConverter.java 2.4 KB
Newer Older
K
Keith Donald 已提交
1
/*
2
 * Copyright 2002-2011 the original author or authors.
K
Keith Donald 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
16

K
Keith Donald 已提交
17 18
package org.springframework.core.convert.support;

K
polish  
Keith Donald 已提交
19
import java.util.Collection;
20 21
import java.util.Collections;
import java.util.Set;
K
polish  
Keith Donald 已提交
22 23

import org.springframework.core.CollectionFactory;
24
import org.springframework.core.convert.ConversionService;
K
Keith Donald 已提交
25
import org.springframework.core.convert.TypeDescriptor;
26
import org.springframework.core.convert.converter.ConditionalGenericConverter;
K
Keith Donald 已提交
27

28
/**
K
Keith Donald 已提交
29 30
 * Converts an Object to a single-element Collection containing the Object.
 * Will convert the Object to the target Collection's parameterized type if necessary.
31 32
 *
 * @author Keith Donald
33
 * @author Juergen Hoeller
34 35
 * @since 3.0
 */
36
final class ObjectToCollectionConverter implements ConditionalGenericConverter {
K
Keith Donald 已提交
37

38
	private final ConversionService conversionService;
K
Keith Donald 已提交
39

40
	public ObjectToCollectionConverter(ConversionService conversionService) {
K
Keith Donald 已提交
41 42
		this.conversionService = conversionService;
	}
K
Keith Donald 已提交
43

44 45
	public Set<ConvertiblePair> getConvertibleTypes() {
		return Collections.singleton(new ConvertiblePair(Object.class, Collection.class));
46 47
	}

48
	public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
49
		return ConversionUtils.canConvertElements(sourceType, targetType.getElementTypeDescriptor(), this.conversionService);
50 51
	}

52
	@SuppressWarnings("unchecked")
53
	public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
54
		if (source == null) {
55
			return null;
56
		}
57
		Collection<Object> target = CollectionFactory.createCollection(targetType.getType(), 1);
58
		if (targetType.getElementTypeDescriptor() == null || targetType.getElementTypeDescriptor().isCollection()) {
59 60 61
			target.add(source);
		}
		else {
62
			Object singleElement = this.conversionService.convert(source, sourceType, targetType.getElementTypeDescriptor());
63
			target.add(singleElement);
64
		}
65
		return target;
K
Keith Donald 已提交
66 67
	}

68
}