From 84f0ddd6bb629f99f6a0683aabad3856a78ea7e6 Mon Sep 17 00:00:00 2001 From: Inderjeet Singh Date: Wed, 1 Apr 2009 22:24:10 +0000 Subject: [PATCH] Throwing a helpful error in cases where the user forgot to use the TypeToken idiom. --- .../java/com/google/gson/TypeInfoFactory.java | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/gson/src/main/java/com/google/gson/TypeInfoFactory.java b/gson/src/main/java/com/google/gson/TypeInfoFactory.java index e02b647d..deb88a2f 100644 --- a/gson/src/main/java/com/google/gson/TypeInfoFactory.java +++ b/gson/src/main/java/com/google/gson/TypeInfoFactory.java @@ -80,18 +80,24 @@ final class TypeInfoFactory { } } } else if (typeToEvaluate instanceof TypeVariable) { - // The class definition has the actual types used for the type variables. - // Find the matching actual type for the Type Variable used for the field. - // For example, class Foo { A a; } - // new Foo(); defines the actual type of A to be Integer. - // So, to find the type of the field a, we will have to look at the class' - // actual type arguments. - TypeVariable fieldTypeVariable = (TypeVariable) typeToEvaluate; - TypeVariable[] classTypeVariables = rawParentClass.getTypeParameters(); - ParameterizedType objParameterizedType = (ParameterizedType) parentType; - int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable); - Type[] actualTypeArguments = objParameterizedType.getActualTypeArguments(); - return actualTypeArguments[indexOfActualTypeArgument]; + if (parentType instanceof ParameterizedType) { + // The class definition has the actual types used for the type variables. + // Find the matching actual type for the Type Variable used for the field. + // For example, class Foo { A a; } + // new Foo(); defines the actual type of A to be Integer. + // So, to find the type of the field a, we will have to look at the class' + // actual type arguments. + TypeVariable fieldTypeVariable = (TypeVariable) typeToEvaluate; + TypeVariable[] classTypeVariables = rawParentClass.getTypeParameters(); + ParameterizedType objParameterizedType = (ParameterizedType) parentType; + int indexOfActualTypeArgument = getIndex(classTypeVariables, fieldTypeVariable); + 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) { WildcardType castedType = (WildcardType) typeToEvaluate; return getActualType(castedType.getUpperBounds()[0], parentType, rawParentClass);