If you try to serialize an object that has a field of type java.lang.Class
, serializing it will lead to java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: <some_class> Forgot to register a type adapter
Below is the code snippet from com.google.gson.internal.bind.TypeAdapters.java
public final class TypeAdapters {
.
.
.
public static final TypeAdapter<Class> CLASS = new TypeAdapter<Class>() {
@Override
public void write(JsonWriter out, Class value) throws IOException {
if (value == null) {
out.nullValue();
} else {
throw new UnsupportedOperationException("Attempted to serialize java.lang.Class: "
+ value.getName() + ". Forgot to register a type adapter?");
}
}
.
.
.
}
Was this coded in gson just to remind people if they "Forgot to register a type adapter"?
As I see it, Class
type object could have easily been serialized and deserialized using the following statements:
Serialize : clazz.getName()
Deserialize : Class.forName(className)
What could the reason behind the current implementation be? Where am I wrong in this?