通过反射创建的对象的不可空字段为空

Non nullable field of object created via reflection is null

我有下一个class结构:

class ExampleResponse(
    @SerializedName("status")
    val status: String
)

我正在通过反射创建此 class 的实例:

fun convert(typeAdapterFactory: TypeAdapterFactory, gson: Gson): Optional<*> {
 return try {
            val genericTypeClassName = "com.example.package.ExampleResponse"
            val genericClass = Class.forName(genericTypeClassName)
            val genericTypeAdapter = gson.getDelegateAdapter(typeAdapterFactory, TypeToken.get(genericClass))
            val response = genericTypeAdapter.fromJson("{}")
            Optional.of(response)
        } catch (e: Exception) {
            Optional.empty<Any>()
        }
}

我正在等待 genericTypeAdapter.fromJson("{}") 行它会抛出异常,因为状态将为空。但是我收到了状态字段为空的 ExampleResponse 实例。 如果状态为空,我想 return Optional.empty() 。我如何在不检查字段的情况下实现这一目标? (检查字段为非 null 是不可接受的,因为真正的功能是通用的,我不知道 class 我会在这里收到什么)。

Gson 不知道字段 can/cannot 何时为空,因为它是一个 Java 库并且 Java 对可空性一无所知。

这个问题和答案提出了一些解决方法: Gson optional and required fields