我有两个这样的课程:
public class User implements Serializable {
String id;
String name;
String email;
String age;
String full_name;
public String getAboutCustomer() {
return aboutCustomer;
}
public void setAboutCustomer(String aboutCustomer) {
this.aboutCustomer = aboutCustomer;
}
String aboutCustomer;
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public void setAge(String age) {
this.age = age;
}
public String getFull_name() {
return full_name;
}
public String getAge() {
return age;
}
public User() {
}
public User(String id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
public class Message implements Serializable {
String id, message, createdAt, type;
User user;
public Message() {
}
public Message(String id, String message, String createdAt, User user) {
this.id = id;
this.message = message;
this.createdAt = createdAt;
this.user = user;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getType(){
return type;
}
public void setType(String type){
this.type = type;
}
}
我希望从他们两个获得一个列表。问题是,我想创建一个适用于两者的方法,因此类的类型不相关。这是我到目前为止所尝试的:
public List<?> getList(){
String s = sharedPrefsLists.getString(SharedPrefsInformation.GET_MAIN_FEED_LIST, null);
return new Gson().fromJson(s,
new TypeToken<List<?>>() {
}.getType());
}
但如果我尝试这样的事情: List lUser = getList();它不起作用。 Android说我必须强制转换,更改变量或使方法返回“User”类型。
如何创建列表而不管对象的类型?
答案 0 :(得分:1)
您可以通过执行以下操作来制作通用方法:
public <T> List<T> getList(){
String s = sharedPrefsLists.getString(SharedPrefsInformation.GET_MAIN_FEED_LIST, null);
return new Gson().fromJson(s,
new TypeToken<List<T>>() {
}.getType());
}
然后调用方法将结果分配给通用列表,如下所示:
List<User> users = getList();
但是,如果不传递共享首选项以查找或以某种方式允许解析不同的JSON字符串,我不知道您希望此方法如何有用。