[英]Why is Kotlin accepting a null value in an attribute declared as a non-nullable string?
I declared a data class
like this:我声明了一个这样的data class
:
data class Product(val name: String = "", val price: Float = 0f)
My code is:我的代码是:
val json = "{'name': null, 'price': 50.00}"
val gson = GsonBuilder().create()
val p = gson.fromJson(json, Product::class.java)
println("name is ${p.name}")
The console output is: name is null
控制台输出为: name is null
How is this possible?这怎么可能? The name attribute is not a nullable string. name 属性不是可为空的字符串。
That's common problem when using Gson with Kotlin - and the runtime errors occur far too late here, which may make your program unstable and crash-friendly.这是在 Kotlin 中使用 Gson 时的常见问题 - 运行时错误在这里发生得太晚了,这可能会使您的程序不稳定且容易崩溃。 For example, write:例如,写:
val name: String = p.name
Boom!繁荣! Crash.碰撞。
Gson simply, as per super hacky implementation , allocates memory for the class without calling the constructor, and later fills fields with values that are present in JSON using reflection. Gson 只是按照super hacky implementation ,在不调用构造函数的情况下为类分配内存,然后使用反射用 JSON 中存在的值填充字段。
This makes it possible to store null
in Kotlin's not-null properties, and that can cause NPE at runtime.这使得在 Kotlin 的非空属性中存储null
成为可能,这可能会在运行时导致 NPE。 You can provide custom TypeAdapter to disable reflection for your class.您可以提供自定义TypeAdapter来禁用您的类的反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.