类文字左侧只允许使用类 [英] only classes are allowed on the left hand side of a class literal

查看:314
本文介绍了类文字左侧只允许使用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在StackOverflow中知道很多类似的问题,但是我的问题没有解决.

I know a lot of similar questions here in StackOverflow, but nothing solved mine.

我有一个通用的数据类:

I have a generic data class:

  data class ServiceCall<out T>(val result: T?, val exception: String?, val pagination: String?, val stringResult: String?)

我正试图这样使用:

Gson().fromJson(json, ServiceCall<SurveyListModel>::class.java).result

IDE显示错误:只允许在类文字的左侧使用类

该如何解决?预先感谢.

How to solve this? Thanks in advance.

推荐答案

您不能在class中使用泛型,因为在这里很容易观察到:

You can't use generics with class, as easily observable here:

List<Int>::class.java

它给您同样的错误.要在GSON反序列化中使用通用类型,请执行以下建议:

It gives you the same error. To use the generic typ in GSON deserialization, do what is suggested here:

https://stackoverflow.com/a/5554296/8073652

在Kotlin中,它看起来像这样:

In Kotlin it looks like this:

val type: Type = object : TypeToken<ServiceCall<SurveyListModel>>() {}.type 
Gson().fromJson<ServiceCall<SurveyListModel>>(json, type).result

这是我写的一个小的概念证明:

Here's a small proof of concept, I've written:

 class Token : TypeToken<List<Int>>()
 val x: List<Int> = Gson().fromJson(Gson().toJson(arrayOf(1)), Token().type)
 println(x)

这篇关于类文字左侧只允许使用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆