Why has gson does not allow serialization of java.lang.Class?

社会主义新天地 提交于 2019-12-12 11:34:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/34026751/why-has-gson-does-not-allow-serialization-of-java-lang-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!