Why doesn't gson allow serialization of java.lang.Class?

If you try to serialize an object with a type field java.lang.Class, serializing it will result injava.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: <some_class> Forgot to register a type adapter

Below is a snippet of code 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 encoded in gson just to remind people if they "Forgot to register type adapter"?

As I see it, an object of type Classcan be easily serialized and deserialized using the following statements:

Serialization: clazz.getName()

Deserialize: Class.forName(className)

What could be the reason for the current implementation? Where am I wrong about this?

+4
source share
1 answer

@Programmer Bruce Gson -

340 Gson :

, . , .json , ; , , .

.

,

, , , "" .

+2

Source: https://habr.com/ru/post/1618153/


All Articles