Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Generics 带有kotlin泛型的Moshi不会为接口抛出JsonAdapter_Generics_Kotlin_Type Erasure_Moshi - Fatal编程技术网

Generics 带有kotlin泛型的Moshi不会为接口抛出JsonAdapter

Generics 带有kotlin泛型的Moshi不会为接口抛出JsonAdapter,generics,kotlin,type-erasure,moshi,Generics,Kotlin,Type Erasure,Moshi,假设我有一个接口IRunnable和两个实现Cat和Dog: interface IRunnable { fun run() } class Cat : IRunnable { override fun run() { println("cat running") } } class Dog : IRunnable { override fun run() { println("dog running") } } 还有一个接口可以将IRunnable转换为Map,其中key=r

假设我有一个接口
IRunnable
和两个实现
Cat
Dog

interface IRunnable {
  fun run()
}

class Cat : IRunnable {
  override fun run() { println("cat running") }
}

class Dog : IRunnable {
  override fun run() { println("dog running") }
}
还有一个接口可以将
IRunnable
转换为
Map
,其中key=
runnable

interface IMapConverter<T> {
  fun getMap(impl : T) : Map<String , String>
  fun getImpl(map : Map<String , String>) : T?
}
它运行良好:

  @Test
  fun testConverter1() {
    val converter = RunnableConverter()

    val moshi = Moshi.Builder()
      .add(converter.getAdapter())
      .build()

    val adapter = moshi.adapter<IRunnable>(IRunnable::class.java)
    adapter.toJson(Dog()).also { json ->
      assertEquals("""{"runnable":"D"}""" , json)
      adapter.fromJson(json).also { runnable ->
        assertTrue(runnable is Dog)
      }
    }
  }
我尝试在Moshi.java的第137行设置断点

这是调试屏幕截图:

OK(在
RunnableConverter
中定义):

这是由扩展函数创建的通用版本:

似乎是因为类型擦除,它无法工作。。。 有没有办法解决这个问题

对于任何对此感兴趣的人,完整代码如下:

环境:

<dependency>
  <groupId>com.squareup.moshi</groupId>
  <artifactId>moshi-kotlin</artifactId>
  <version>1.9.2</version>
</dependency>

com.squareup.moshi
莫希·科特林
1.9.2
谢谢。

选项1(我希望它能工作,但不确定):尝试将
toJsonAdapter
更改为
inline fun IMapConverter.toJsonAdapter():JsonAdapter{…}

选项2:使用一个
Moshi.Builder.add
重载,允许指定类型(
Class
extends
type
):

为避免出现输入错误类型的机会,您可以再次使用
reified

inline fun <reified T> Moshi.Builder.add(converter: IMapConverter<T>) = add(T::class.java, converter.toJsonAdapter())

您需要使用
@JvmSuppressWildcards
抑制通配符

你的情况应该是这样的

interface IMapConverter<@JvmSuppressWildcards T> {
  fun getMap(impl : T) : Map<String , String>
  fun getImpl(map : Map<String , String>) : T?
}
接口IMapConverter{
趣味地图(impl:T):地图
有趣的getImpl(地图:地图):T?
}

是的,Moshi需要能够反思T在这里是什么。我推荐备选方案2的一种变体;返回JsonAdapter的实例,而不是带有注释方法的对象。选项1也使用JsonAdapter的实例,
具体化的要点是它应该继承
JsonAdapter
,而不是
JsonAdapter
。谢谢,这两个选项都很好用!我从未想过具体化的解决方案。
  @Test
  fun testConverter2() {
    val converter = RunnableConverter()

    val moshi = Moshi.Builder()
      .add(converter.toJsonAdapter()) // this is extension function
      .build()

    val adapter = moshi.adapter<IRunnable>(IRunnable::class.java)
    adapter.toJson(Dog()).also { json ->
      logger.info("json of dog = {}", json)
      assertEquals("""{"runnable":"D"}""" , json)
      adapter.fromJson(json).also { runnable ->
        assertTrue(runnable is Dog)
      }
    }
  }
java.lang.IllegalArgumentException: No JsonAdapter for interface moshi.IRunnable (with no annotations)

    at com.squareup.moshi.Moshi.adapter(Moshi.java:148)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:98)
    at com.squareup.moshi.Moshi.adapter(Moshi.java:72)
    at moshi.MoshiTest.testConverter2(MoshiTest.kt:39)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
<dependency>
  <groupId>com.squareup.moshi</groupId>
  <artifactId>moshi-kotlin</artifactId>
  <version>1.9.2</version>
</dependency>
.add(IRunnable::class.java, converter.toJsonAdapter())
inline fun <reified T> Moshi.Builder.add(converter: IMapConverter<T>) = add(T::class.java, converter.toJsonAdapter())
Moshi.Builder().add(converter)
interface IMapConverter<@JvmSuppressWildcards T> {
  fun getMap(impl : T) : Map<String , String>
  fun getImpl(map : Map<String , String>) : T?
}