Revised getRuntimeTypeIfMoreSpecific to ignore the parent and just focus on the value.

All uses of this method have already made a determination about the parent.
This commit is contained in:
Inderjeet Singh 2011-08-05 00:13:01 +00:00
parent 64dc53ffc4
commit e9a971f680
4 changed files with 7 additions and 11 deletions

View File

@ -88,7 +88,7 @@ public final class ArrayTypeAdapter<E> extends TypeAdapter<Object> {
writer.beginArray();
for (int i = 0, length = Array.getLength(array); i < length; i++) {
final E value = (E) Array.get(array, i);
Type runtimeType = Reflection.getRuntimeTypeIfMoreSpecific(componentType, array, value);
Type runtimeType = Reflection.getRuntimeTypeIfMoreSpecific(componentType, value);
TypeAdapter t = runtimeType != componentType ?
context.getAdapter(TypeToken.get(runtimeType)) : componentTypeAdapter;
t.write(writer, value);

View File

@ -107,7 +107,7 @@ public final class CollectionTypeAdapter<E> extends TypeAdapter<Collection<E>> {
writer.beginArray();
for (E element : collection) {
Type runtimeType = Reflection.getRuntimeTypeIfMoreSpecific(elementType, collection, element);
Type runtimeType = Reflection.getRuntimeTypeIfMoreSpecific(elementType, element);
TypeAdapter t = runtimeType != elementType ?
context.getAdapter(TypeToken.get(runtimeType)) : elementTypeAdapter;
t.write(writer, element);

View File

@ -23,15 +23,11 @@ import java.lang.reflect.TypeVariable;
final class Reflection {
/**
* Finds a compatible runtime type if it is more specific
* In case of a field of an object, parent is the object instance, and child is the field value.
* In case of an Array, parent is the array instance, and the child is the array element.
*/
public static Type getRuntimeTypeIfMoreSpecific(Type type, Object parent, Object child) {
if (parent == null || child == null) {
return type;
}
if (type == Object.class || type instanceof TypeVariable || type instanceof Class<?>) {
type = (Class<?>) child.getClass();
public static Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {
if (value != null
&& (type == Object.class || type instanceof TypeVariable || type instanceof Class<?>)) {
type = (Class<?>) value.getClass();
}
return type;
}

View File

@ -122,7 +122,7 @@ public final class ReflectiveTypeAdapter<T> extends TypeAdapter<T> {
throws IOException, IllegalAccessException {
Object fieldValue = field.get(value);
Type declaredTypeOfField = fieldType.getType();
Type resolvedTypeOfField = Reflection.getRuntimeTypeIfMoreSpecific(declaredTypeOfField, value, fieldValue);
Type resolvedTypeOfField = Reflection.getRuntimeTypeIfMoreSpecific(declaredTypeOfField, fieldValue);
TypeAdapter t = resolvedTypeOfField != declaredTypeOfField ?
context.getAdapter(TypeToken.get(resolvedTypeOfField)) : this.typeAdapter;
t.write(writer, fieldValue);