Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Marcono1234 opened this issue May 25, 2020 · 1 comment · May be fixed by #2068
Labels

Comments

@Marcono1234
Copy link
Collaborator

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?

@Marcono1234
Copy link
Collaborator Author

Marcono1234 commented Jul 28, 2022

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
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant