我正在尝试在Jersey中编写一个通用函数,该函数可用于通过REST获取相同类型的对象列表。我基于此论坛中的信息进行链接:
@Override public <T> List<T> fetchResourceAsList(String url) { ClientConfig cc = new DefaultClientConfig(); Client c = Client.create(cc); if (userName!=null && password!=null) { c.addFilter(new HTTPBasicAuthFilter(userName, password)); } WebResource resource = c.resource(url); return resource.get(new GenericType<List<T>>() {}); }
但是,这不起作用。如果我尝试执行它,则会出现以下错误:SEVERE: A message body reader for Java class java.util.List, and Java type java.util.List<T>, and MIME media type application/xml was not found。
SEVERE: A message body reader for Java class java.util.List, and Java type java.util.List<T>, and MIME media type application/xml was not found
但是,如果我编写此函数时没有进行模板化(用实际的类名替换T),则可以正常工作。当然,这种方式会使函数失去其意义。
有没有办法解决这个问题?
我找到了解决方案 https://java.net/projects/jersey/lists/users/archive/2011-08/message/37
public <T> List<T> getAll(final Class<T> clazz) { ParameterizedType parameterizedGenericType = new ParameterizedType() { public Type[] getActualTypeArguments() { return new Type[] { clazz }; } public Type getRawType() { return List.class; } public Type getOwnerType() { return List.class; } }; GenericType<List<T>> genericType = new GenericType<List<T>>( parameterizedGenericType) { }; return service.path(Path.ROOT).path(clazz.getSimpleName()) .accept(MediaType.APPLICATION_XML).get(genericType); }