Throwing a helpful error in cases where the user forgot to use the TypeToken idiom.

This commit is contained in:
Inderjeet Singh 2009-04-01 22:24:10 +00:00
parent 5c6d5a0d11
commit 84f0ddd6bb

View File

@ -80,18 +80,24 @@ final class TypeInfoFactory {
} }
} }
} else if (typeToEvaluate instanceof TypeVariable) { } else if (typeToEvaluate instanceof TypeVariable) {
// The class definition has the actual types used for the type variables. if (parentType instanceof ParameterizedType) {
// Find the matching actual type for the Type Variable used for the field. // The class definition has the actual types used for the type variables.
// For example, class Foo<A> { A a; } // Find the matching actual type for the Type Variable used for the field.
// new Foo<Integer>(); defines the actual type of A to be Integer. // For example, class Foo<A> { A a; }
// So, to find the type of the field a, we will have to look at the class' // new Foo<Integer>(); defines the actual type of A to be Integer.
// actual type arguments. // So, to find the type of the field a, we will have to look at the class'
TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate; // actual type arguments.
TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters(); TypeVariable<?> fieldTypeVariable = (TypeVariable<?>) typeToEvaluate;
ParameterizedType objParameterizedType = (ParameterizedType) parentType; TypeVariable<?>[] classTypeVariables = rawParentClass.getTypeParameters();
int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable); ParameterizedType objParameterizedType = (ParameterizedType) parentType;
Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments(); int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable);
return actualTypeArguments[indexOfActualTypeArgument]; Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments();
return actualTypeArguments[indexOfActualTypeArgument];
} else {
throw new UnsupportedOperationException("Expecting parameterized type, got " + parentType
+ ".\n Are you missing the use of TypeToken idiom?\n See "
+ "http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener");
}
} else if (typeToEvaluate instanceof WildcardType) { } else if (typeToEvaluate instanceof WildcardType) {
WildcardType castedType = (WildcardType) typeToEvaluate; WildcardType castedType = (WildcardType) typeToEvaluate;
return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass); return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);