4

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?

tunetopj
  • 561
  • 2
  • 5
  • 15
  • Possible duplicate of [Gson not parsing Class variable](http://stackoverflow.com/questions/8119138/gson-not-parsing-class-variable) – wero Dec 01 '15 at 17:56
  • Yes, Thanks. Seems like the question is asking the same question. I suppose the description in my question clears some confusions. I'll use the answer there to answer this question myself. – tunetopj Dec 01 '15 at 18:10

1 Answers1

2

as answered by @Programmer Bruce Gson not parsing Class variable -

In a comment in issue 340, a Gson project manager explains:

Serializing types is actually somewhat of a security problem, so we don't want to support it by default. A malicious .json file could cause your application to load classes that it wouldn't otherwise; depending on your class path loading certain classes could DoS your application.

But it's quite straightforward to write a type adapter to support this in your own app.

Of course, since serialization is not the same as

deserialization, I don't understand how this is an explanation for the disabled serialization, unless the unmentioned notion is to in a sense "balance" the default behaviors of serialization with deserialization.

Community
  • 1
  • 1
tunetopj
  • 561
  • 2
  • 5
  • 15