Restore ability of instance creators to create collection and map types. We inadvertently lost this in Gson 2.0 and 2.1. Nobody noticed!

This commit is contained in:
Jesse Wilson 2012-01-01 15:46:33 +00:00
parent 6cca23c172
commit bb8dca71c4
2 changed files with 21 additions and 5 deletions

View File

@ -194,10 +194,6 @@ public final class Gson {
this.htmlSafe = htmlSafe; this.htmlSafe = htmlSafe;
this.prettyPrinting = prettyPrinting; this.prettyPrinting = prettyPrinting;
TypeAdapterFactory reflectiveTypeAdapterFactory = new ReflectiveTypeAdapterFactory(
constructorConstructor, fieldNamingPolicy, excluder);
ConstructorConstructor constructorConstructor = new ConstructorConstructor();
List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>(); List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>();
// built-in type adapters that cannot be overridden // built-in type adapters that cannot be overridden
@ -242,7 +238,8 @@ public final class Gson {
factories.add(ArrayTypeAdapter.FACTORY); factories.add(ArrayTypeAdapter.FACTORY);
factories.add(TypeAdapters.ENUM_FACTORY); factories.add(TypeAdapters.ENUM_FACTORY);
factories.add(TypeAdapters.CLASS_FACTORY); factories.add(TypeAdapters.CLASS_FACTORY);
factories.add(reflectiveTypeAdapterFactory); factories.add(new ReflectiveTypeAdapterFactory(
constructorConstructor, fieldNamingPolicy, excluder));
this.factories = Collections.unmodifiableList(factories); this.factories = Collections.unmodifiableList(factories);
} }

View File

@ -23,6 +23,9 @@ import com.google.gson.common.TestTypes.Base;
import com.google.gson.common.TestTypes.ClassWithBaseField; import com.google.gson.common.TestTypes.ClassWithBaseField;
import com.google.gson.common.TestTypes.Sub; import com.google.gson.common.TestTypes.Sub;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import junit.framework.TestCase; import junit.framework.TestCase;
import java.lang.reflect.Type; import java.lang.reflect.Type;
@ -79,4 +82,20 @@ public class InstanceCreatorTest extends TestCase {
assertTrue(target.base instanceof Sub); assertTrue(target.base instanceof Sub);
assertEquals(Sub.SUB_NAME, ((Sub)target.base).subName); assertEquals(Sub.SUB_NAME, ((Sub)target.base).subName);
} }
// This regressed in Gson 2.0 and 2.1
public void testInstanceCreatorForCollectionType() {
class SubArrayList<T> extends ArrayList<T> {}
InstanceCreator<List<String>> listCreator = new InstanceCreator<List<String>>() {
public List<String> createInstance(Type type) {
return new SubArrayList<java.lang.String>();
}
};
Type listOfStringType = new TypeToken<List<String>>() {}.getType();
Gson gson = new GsonBuilder()
.registerTypeAdapter(listOfStringType, listCreator)
.create();
List<String> list = gson.fromJson("[\"a\"]", listOfStringType);
assertEquals(SubArrayList.class, list.getClass());
}
} }