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

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>() {
    public void write(JsonWriter out, Class value) throws IOException {
      if (value == null) {
      } 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?


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.

Need Your Help

Optimizing a LAN server for a game

c++ c optimization networking network-programming

I'm the network programmer on a school game project. We want to have up to 16 players at once on a LAN. I am using the Server-Client model and am creating a new thread per client that joins. How...