我使用此通用方法使用此接口:
interface IInterface {
fun <T> test(body: T)
}
我想这样实现此接口:
class MyClass: IInterface {
override fun <JsonObject> test(body: JsonObject) {
if (body is com.google.gson.JsonObject) {
}
}
}
我的问题是JsonObject类型无法识别,例如“ com.google.gson.JsonObject”。因此,我可以在编译器(intelliJ)中编写此代码而不会出错。
override fun <NotExistingClass__> test(body: NotExistingClass__) {
那么,如何从Gson定义JsonObject的T类型?此代码不起作用:
override fun <com.google.gson.JsonObject> test(body: com.google.gson.JsonObject)
谢谢
答案 0 :(得分:2)
此interface
:
interface IInterface {
fun <T> test(body: T)
}
不是通用的,但是具有通用的方法。如果要使其通用,请执行以下操作:
interface IInterface<T> {
fun test(body: T)
}
然后您的实现将如下所示:
class MyClass: IInterface<JsonObject> {
override fun test(body: JsonObject) {
if (body is com.google.gson.JsonObject) {
}
}
}
如果由于某种原因仍需要通用方法,则必须在每个调用站点传递通用类型参数:
someInstance.test<JsonObject>(obj)