DeX*_*eX3 3 jersey jackson dropwizard
我想实现一个泛型类,用于缓存本地MongoDB实例中REST API的结果.为此,我需要反序列化我从JerseyClient获得的集合:
Response response = this.source.request().get();
List<T> list = response.readEntity( new GenericType<List<T>>() {} );
// ... do stuff with the list
Run Code Online (Sandbox Code Playgroud)
假设我在T与类相关的上下文中使用了这段代码Foo.非常奇怪的是,在readEntity通话之后,list不是一个List<Foo>,而是一个List<LinkedHashMap>.当我明确宣布Generic T是Foo什么时,这怎么可能呢?
我该怎样做才能得到一个合适的List<T>,即List<Foo>呢?
注意:如果我删除了泛型,并使用
List<Foo> list = response.readEntity( new GenericType<List<Foo>>() {} );
Run Code Online (Sandbox Code Playgroud)
直接相反,它工作正常,但我真的需要那个通用的存在!
Java是泛型中最受欢迎的借口:Type Erasure
如果您可以将类类型传递给Class<T> clazz,那么您可以使用:
GenericType<List<T>> genericType = new GenericType<>(new ParameterizedType() {
public Type[] getActualTypeArguments() {
return new Type[]{clazz};
}
public Type getRawType() {
return List.class;
}
public Type getOwnerType() {
return null;
}
});
response.readEntity(genericType);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1112 次 |
| 最近记录: |