gpt4 book ai didi

java - 为什么 gson 不允许序列化 java.lang.Class?

转载 作者:搜寻专家 更新时间:2023-11-01 03:19:50 24 4
gpt4 key购买 nike

如果您尝试序列化一个字段类型为 java.lang.Class 的对象, 序列化它会导致 java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: <some_class> Forgot to register a type adapter

下面是来自 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?");
}
}
.
.
.
}

这是在 gson 中编码只是为了提醒人们“忘记注册类型适配器”吗?

如我所见,Class类型对象可以使用以下语句轻松地序列化和反序列化:

序列化:clazz.getName()

反序列化:Class.forName(className)

当前实现背后的原因是什么?我哪里错了?

最佳答案

由@Programmer Bruce 回答Gson not parsing Class variable -

comment in issue 340 中,一位 Gson 项目经理解释道:

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.

当然,既然连载不一样

反序列化,我不明白这是怎么解释的禁用序列化,除非未提及的概念在某种意义上是“平衡”序列化与反序列化的默认行为。

关于java - 为什么 gson 不允许序列化 java.lang.Class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34026751/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com