【发布时间】:2014-01-22 14:10:41
【问题描述】:
Gson 2.2.2 无法序列化 Object1 中的字段。
public class Test {
public static void main(String[] args){
Object1 o1 = new Object1();
List<Interface1> list1 = new ArrayList<Interface1>();
Interface1 f1 = new InterfaceImp();
list1.add(f1);
o1.field = list1;
System.out.println(new Gson().toJson(o1));
}
}
interface Interface1{}
class InterfaceImp implements Interface1{
public String s = "123";
}
class Object1 {
public List<? extends Interface1> field ;
}
调试的时候发现TypeAdapterRuntimeTypeWrapper中的方法:
private Type getRuntimeTypeIfMoreSpecific(Type type, Object value) {
if (value != null && (type == Object.class || type instanceof TypeVariable<?> || type instanceof Class<?>)) {
type = value.getClass();
}
return type;
}
不返回 value.getClass()。 arg 'type'(? extends Interface1) 使 if 测试变得错误。一个错误?
【问题讨论】:
-
嗯,what 类型你希望它返回,究竟是什么?您正在使用有界通配符,这意味着您没有类型。你……不能那样做。
标签: java serialization gson