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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.