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

查看:30
本文介绍了Dropwizard 反序列化来自 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

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?

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's most popular excuse for Generics: Type Erasure

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

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

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