Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

android - only classes are allowed on the left hand side of a class literal

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?)

I am trying to use like this:

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

IDE shows error: only classes are allowed on the left hand side of a class literal

How to solve this? Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

List<Int>::class.java

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

EDIT:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...