I have next class structure:
class ExampleResponse(
@SerializedName("status")
val status: String
)
I am creating instance of this class via reflection:
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>()
}
}
I am waiting that on the line genericTypeAdapter.fromJson("{}")
it will throw exception, because status will be null. But I am receiving instance of ExampleResponse with null status field. I want to return Optional.empty() if status is null. How can I achieve this without checking fields? (checking field to non null is not acceptable because the real function is universal and I won't know what class I'll receive here).
Aucun commentaire:
Enregistrer un commentaire