PageRenderTime 16ms CodeModel.GetById 12ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/sitebricks-converter/src/main/java/com/google/sitebricks/conversion/MvelTypeConverter.java

http://github.com/dhanji/sitebricks
Java | 54 lines | 39 code | 6 blank | 9 comment | 10 complexity | cf9ca08aff030b38a2f8414f4e0714eb MD5 | raw file
 1package com.google.sitebricks.conversion;
 2
 3import java.lang.reflect.Array;
 4import java.lang.reflect.GenericArrayType;
 5import java.lang.reflect.ParameterizedType;
 6import java.lang.reflect.Type;
 7import java.lang.reflect.TypeVariable;
 8
 9import org.mvel2.DataConversion;
10
11import com.google.inject.Singleton;
12import com.google.sitebricks.conversion.TypeConverter;
13
14/**
15 * @author John Patterson (jdpatterson@gmail.com)
16 *
17 */
18@Singleton
19public class MvelTypeConverter implements TypeConverter {
20 	
21	@Override @SuppressWarnings("unchecked")
22	public <T> T convert(Object source, Type type) {
23		return (T) DataConversion.convert(source, erase(type));
24	}
25
26	/**
27	 * Returns the erasure of the given type.
28	 * Taken from GenTyRef project
29	 * TODO replace this once Sitebricks has internal generics utils
30	 */
31	public static Class<?> erase(Type type) {
32		if (type instanceof Class<?>) {
33			return (Class<?>) type;
34		}
35		else if (type instanceof ParameterizedType) {
36			return (Class<?>) ((ParameterizedType) type).getRawType();
37		}
38		else if (type instanceof TypeVariable<?>) {
39			TypeVariable<?> tv = (TypeVariable<?>) type;
40			if (tv.getBounds().length == 0)
41				return Object.class;
42			else
43				return erase(tv.getBounds()[0]);
44		}
45		else if (type instanceof GenericArrayType) {
46			GenericArrayType aType = (GenericArrayType) type;
47			Class<?> componentType = erase(aType.getGenericComponentType());
48			return Array.newInstance(componentType, 0).getClass();
49		}
50		else {
51			throw new RuntimeException("not supported: " + type.getClass());
52		}
53	}
54}