ChineSouad / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Make GsonBuilde.registerTypeAdapter() method more concrete #276

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
I'd like to suggest one enhancement.

As described in docs:
http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/G
sonBuilder.html#registerTypeAdapter(java.lang.reflect.Type,%20java.lang.Object)
method registerTypeAdapter receive second argument of type Object,
which is wired (at least for me), code didn't tells me what I should
pass as actual parameter so I should consider documentation first.

-------------
Here is my plan.
1. Declare abstract interface:
package com.google.gson;
public abstract interface TypeAdapter<T> {
  //emty body
  //Note: abstract interface can not be implemented directrly.
}

2. Inherit InstanceCreator, JsonSerializer, and a JsonDeserializer from
TypeAdapter, like this:
public interface InstanceCreator<T> extends TypeAdapter<T>
public interface JsonSerializer<T> extends TypeAdapter<T>
public interface JsonDeserializer <T> extends TypeAdapter<T>

3. Change registerTypeAdapter method signature to:
registerTypeAdapter(java.lang.reflect.Type,TypeAdapter<T>)
//note: something might be done to handle type T more precisely
//to check that TypeAdapter type corresponds to first agrument.
//But I'm not sure.

4. As result it will be clear for gson llibrary users - what should
be passed as typaAdapter.

Original issue reported on code.google.com by dmitry.s...@gmail.com on 13 Jan 2011 at 4:56

GoogleCodeExporter commented 9 years ago
We have methods like that (though marked private) registerSerializer, 
registerDeserializer, etc. 

It seems type-safe but with a false sense of security. Unfortunately, Java Type 
class is not parameterized, so it is possible for you to attach a 
TypeAdapter<T> with any type instead of the type of T.  We can address that by 
providing registerSerializer(Class<T>, JsonSerializer<T>) but that excludes the 
possibility of registering type adapters for parameterized types.  Providing 
both methods results in unnecessary API bloat. 

I think what we currently have is a reasonable solution but if you can think of 
a minimalist enhancement that improves type safety, let us know. 

Original comment by inder123 on 19 Jan 2011 at 10:16