我对泛型方法的显式类型参数有问题.我知道我可以这样做:
Foo.<Bar>function();
Run Code Online (Sandbox Code Playgroud)
假设有一个
void <T> function() {...}
Run Code Online (Sandbox Code Playgroud)
在Foo类中的函数.确切的问题是:
我想下载一些内容(带有Ion的 Android )
这些内容类似(Article,BlogArticle,...),都实现了ContentItem接口
目前下载如下:
例如新闻
private void downloadNews() {
Ion.with(this)
.load(URL_NEWS)
.as(new TypeToken<List<Article>>(){})
.setCallback(new FutureCallback<List<Article>>() {
@Override
public void onCompleted(Exception e, List<Article> result) {
// do something with result
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果我想下载博客文章,我必须更改网址和文章类(对于BlogArticle).
我试着像这样制作一个通用函数:
private <T extends ContentItem> void download(String url) {
Ion.with(this)
.load(url)
.as(new TypeToken<List<T>>(){})
.setCallback(new FutureCallback<List<T>>() {
@Override
public void onCompleted(Exception e, List<T> result) {
// do something with result
}
});
}
Run Code Online (Sandbox Code Playgroud)
并调用该函数
this.<Article>download(url);
Run Code Online (Sandbox Code Playgroud)
没关系,编译得很好.跑完后我得到了
java.lang.ClassCastException:com.google.gson.internal.LinkedTreeMap无法强制转换为com.my.packagename.model.ContentItem
问题是它没有使用显式类将Json映射到pojo. …
我有一个简单的层次结构,包含以下内容:
它们都应该与 Kotlinx 序列化一起使用。一切都很顺利,直到我添加了Backpack课程。我使用1.4.32Kotlinx 序列化版本。
这是我的类层次结构的详细信息
// Items.kt
@Serializable
sealed class BaseItem {
abstract val id: String
abstract val type: ItemType
abstract var brand: String
abstract var model: String
abstract var imageLink: String
abstract var traits: MutableList<Trait>
abstract var implicitTraits: MutableList<Trait>
abstract var details: MutableMap<String, String>
}
@Serializable
open class Item(
override val id: String = UUID.randomUUID().toString(),
override val type: ItemType = ItemType.UNDEFINED,
override var brand: String, …Run Code Online (Sandbox Code Playgroud)