Skip to content

ConstructorConstructor.newDefaultImplementationConstructor(Type, Class<? super T>) breaks symmetry #1708

Closed

Description

@Marcono1234

The method com.google.gson.internal.ConstructorConstructor.newDefaultImplementationConstructor(Type, Class<? super T>) breaks symmetry.

Normally it is desired that if you can serialize obj as A, then you should be able to deserialize it as A again. This is however not possible if A extends / implements one of the types checked in newDefaultImplementationConstructor and does not have a no-arg constructor.
Example:

static class MyList extends ArrayList<Integer>{
  // Any constructor with parameters to prevent default constructor
  public MyList(int i) {}
}
public void testCustomList() {
  Gson gson = new Gson();
  MyList list = new MyList(1);
  list.add(1);
  String json = gson.toJson(list);
  // java.lang.ClassCastException: Cannot cast java.util.ArrayList to MyList
  gson.fromJson(json, MyList.class);
}

The proper fix would be to have newDefaultImplementationConstructor only create instances if the requested type is the type it creates (e.g. it creates ArrayList and ArrayList is requested) or if the requested type is a supertype of the created one (e.g. it creates ArrayList and List is requested).
Similarly CollectionTypeAdapterFactory would have to be adjusted to only support these types and types for which a constructor has been registered or types which have a default (= no-arg) constructor.

This would in theory not cause any issues if people already serialized and deserialized their objects and therefore the types they are using are matching the above stated requirements.

However, there might be cases where people only serialize objects (such as MyList in the example above), which would break with such a change.

Would it make sense to instead introduce an option to GsonBuilder to prevent serialization which is not symmetric? So people can catch such issues early?

Activity

  1. Marcono1234 commented on Jul 28, 2022

    @Marcono1234
    ContributorAuthor

    Maybe a duplicate of / closely related to #419

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions