gpt4 book ai didi

android - 错误 : Cannot use unbound generics in Type Converters

转载 作者:行者123 更新时间:2023-12-04 23:37:40 26 4
gpt4 key购买 nike

我正在使用 Room 做数据持久化,我想要的是有两种方法

调用stringToObject(String data)

处理多个类的所有类型转换

喜欢:MoviesList & ReviewList & TrailerList
当我运行应用程序时,出现此错误:

error: Cannot use unbound generics in Type Converters.


public class Converters{
public static Gson gson = new Gson();

@TypeConverter
public static <T> List<T> stringToObject(String data) {
if (data == null) {
return Collections.emptyList();
}

Type listType = new TypeToken<List<T>>(){}.getType();

return gson.fromJson(data, listType);
}

@TypeConverter
public static <T> String ObjectToString(List<T> someObjects) {
return gson.toJson(someObjects);
}
}
public class ReviewList {

@SerializedName("id")
private Integer id;
@SerializedName("page")
private Integer page;
@SerializedName("results")
private List<Review> reviewList = null;
@SerializedName("total_pages")
private Integer totalPages;
@SerializedName("total_results")
private Integer totalResults;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public Integer getPage() {
return page;
}

public void setPage(Integer page) {
this.page = page;
}

public List<Review> getReviewList() {
return reviewList;
}

public void setReviewList(List<Review> reviewList) {
this.reviewList = reviewList;
}

....

}
public class TrailerList {

@SerializedName("id")
private Integer id;
@SerializedName("results")
private List<Trailer> trailers = null;

public List<Trailer> getTrailers() {
return trailers;
}

public void setTrailers(List<Trailer> trailers) {
this.trailers = trailers;
}

....

什么是诅咒错误?

我该如何解决?

最佳答案

是的!这是可能的! 对于想要使用 generic type converters 的其他人对于房间,这是我的方法:

public abstract class BaseConverter<T> {

private final Gson gson;
private final Type type;

public BaseConverter(Type type) {
this.type = type;

this.gson = new GsonBuilder()
.serializeNulls()
.setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
.create();
}

@TypeConverter
public List<T> mapStringToList(String value) {
return gson.fromJson(value, type);
}

@TypeConverter
public String mapListToString(List<T> value) {
return gson.toJson(value, type);
}

}
现在您可以创建自己的转换器。例如:
public class UserConverter extends BaseConverter<User> {

public UserConverter() {
super(new TypeToken<List<User>>() {}.getType());
}
}
然后将您的类型转换器添加到房间配置中:
@TypeConverters({
UserConverter.class
})
public abstract class RoomDB extends RoomDatabase {
// ...
}

关于android - 错误 : Cannot use unbound generics in Type Converters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53788263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com