Kotlin泛型 1.reified的作用 https://github.com/JetBrains/kotlin/blob/master/spec-docs/reified-type-parameters.md
支持通过方法传递的类型运行时可用可达
由于java泛型是伪泛型,为了兼容java1.5以前的版本,java运行时,会泛型擦除 会擦除为泛型上界,如果没有泛型上界会擦除为Object,所以jvm在程序运行时是不知道泛型的真实类型, reifield 能保证运行时依然能拿到泛型的具体类型.(当前只限制支持内联函数可用)
1 2 3 4 5 6 7 8 9 10 11 # Reified Type Parameters Goal: support run-time access to types passed to functions, as if they were reified (currently limited to inline functions only). ## Syntax A type parameter of a function can be marked as `reified`: inline fun foo<reified T>() {}
2.实际使用 Activity定义扩展函数
1 2 3 4 5 6 7 8 9 10 inline fun <reified T : Activity> Activity.startActivityKtx () { this .startActivity(Intent(this , T::class .java )) } inline fun <reified T : Activity> Activity.startActivityKtxWithParam (block: (intent : Intent ) -> Any) { val intent = Intent(this , T::class .java ) block.invoke(intent) this .startActivity(intent) }
调用
1 2 3 4 5 6 7 8 startActivityKtxWithParam<TemplateListActivity> { it.putExtra(TemplateListActivity.KEY_CATEGORY_NAME, datas[position].categoryName) } startActivityKtx<MoreActivity>()
如果不用reifield 我们的写法是
1 2 3 fun Activity.startActivityKtx(cls: Class<*>) { this.startActivity(Intent(this, cls)) }
调用是
1 startActivityKtx(Intent(this, MoreActivity::class.java))
String定义扩展函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 inline fun <reified T> String.jsonToObj(): T? { return try { val g = Gson() val type = object : TypeToken<T>() {}.type g.fromJson<T>(this, type) } catch (e: Exception) { null } } inline fun <reified T> String.jsonToObjList(): ArrayList<T>? { return try { val g = Gson() val type = object : TypeToken<ArrayList<T>>() {}.type return g.fromJson<ArrayList<T>>(this, type) } catch (e: Exception) { null } }
json string直接转对象
1.json 格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 [ { "pic" : "classic_08" , "name" : "classic" }, { "pic" : "polygon_04" , "name" : "polygon" }, { "pic" : "quote_02" , "name" : "quote" }, { "pic" : "simple_03" , "name" : "simple" }, { "pic" : "travel_07" , "name" : "travel" }, { "pic" : "marble_06" , "name" : "marble" }, { "pic" : "cloud_08" , "name" : "cloud" }, { "pic" : "freedom_03" , "name" : "freedom" } ]
2.bean
1 2 @Parcelize data class TemplateCategoryItemInfo(@SerializedName("pic") var categoryCoverPic: String, @SerializedName("name") var categoryName: String) : Parcelable
3.string 2 bean (assets2String.jsonToObjList() )
1 2 3 4 5 6 7 class CategoryModel : IModel { fun getData(): ArrayList<TemplateCategoryItemInfo>? { val assets2String = ResourceUtils.readAssets2String("category.json") return assets2String.jsonToObjList() } }
不使用reifeild
1 2 3 4 5 6 7 8 9 fun <T> String.jsonToObj2(): T? { return try { val g = Gson() val type = object : TypeToken<T>() {}.type g.fromJson<T>(this, type) } catch (e: Exception) { null } }
可以看出Gson 在解析时是没有判断出泛型T的真实类型的
使用reifeild
参考 reified-type-parameters.md
[译]Kotlin的独门秘籍Reified实化类型参数(上篇)
我与 Kotlin 的爱恨情仇之浅谈 reified