import jodd.util.ReflectUtil; //导入方法依赖的package包/类
/**
* Converts an object to destination type. If type is registered, it's
* {@link TypeConverter} will be used. If not, it scans of destination is
* an array or enum, as those two cases are handled in a special way.
*
* If destination type is one of common types, consider using {@link jodd.typeconverter.Convert}
* instead for somewhat faster approach (no lookup).
*/
@SuppressWarnings({"unchecked"})
public T convertType(Object value, Class destinationType) {
if (destinationType == Object.class) {
// no conversion :)
return (T) value;
}
TypeConverter converter = lookup(destinationType);
if (converter != null) {
return (T) converter.convert(value);
}
// no converter
if (value == null) {
return null;
}
// handle destination arrays
if (destinationType.isArray()) {
ArrayConverter arrayConverter = new ArrayConverter(this, destinationType.getComponentType());
return (T) arrayConverter.convert(value);
}
// handle enums
if (destinationType.isEnum()) {
Object[] enums = destinationType.getEnumConstants();
String valStr = value.toString();
for (Object e : enums) {
if (e.toString().equals(valStr)) {
return (T) e;
}
}
}
// check same instances
if (ReflectUtil.isInstanceOf(value, destinationType)) {
return (T) value;
}
// collection
if (ReflectUtil.isTypeOf(destinationType, Collection.class)) {
// component type is unknown because of Java's type-erasure
CollectionConverter collectionConverter =
new CollectionConverter(this, destinationType, Object.class);
return (T) collectionConverter.convert(value);
}
// fail
throw new TypeConversionException("Conversion failed: " + destinationType.getName());
}