从JerseyClient反序列化通用列表的Dropwizard [英] Dropwizard deserializing generic list from JerseyClient

查看:77
本文介绍了从JerseyClient反序列化通用列表的Dropwizard的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个泛型类,用于缓存本地MongoDB实例中REST API的结果。为此,我需要反序列化我从JerseyClient获得的集合:

I wanted to implement a generic class to use for caching results from a REST API in a local MongoDB-instance. For this to work, I need to deserialize a collection I get from JerseyClient:

Response response = this.source.request().get();
List<T> list = response.readEntity( new GenericType<List<T>>() {} );

// ... do stuff with the list

让我说我我在 T 的上下文中使用这段代码与类 Foo 相关。非常奇怪的是,在 readEntity 调用之后, list 不是列表< Foo> ; ,而是列表< LinkedHashMap> 。当我明确宣布Generic T Foo

Let's say I'm using this piece of code in a context of T relating to a class Foo. The really weird thing is, after the readEntity call, list is not a List<Foo>, instead is a List<LinkedHashMap>. How is that even possible, when I've clearly declared the Generic T to be Foo?

我需要做些什么来获得正确的列表< T> ,即列表< Foo> 而不是?

What do I have to do to get a proper List<T>, i.e. List<Foo> instead?

注意:如果我删除了通用,请使用

Note: If I remove the generic, and use

List<Foo> list = response.readEntity( new GenericType<List<Foo>>() {} );

直接替代,它工作正常,但我真的需要那个通用的存在!

directly instead, it works fine, but I really need that generic to be there!

推荐答案

Java最普遍的泛型借口:类型擦除

Java's most popular excuse for Generics: Type Erasure

如果您可以将类类型传递为 Class< T> clazz ,然后你可以使用它:

If you can pass your class type as Class<T> clazz, then you can use this:

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);

这篇关于从JerseyClient反序列化通用列表的Dropwizard的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆