2013-05-14 134 views
1

通过泛型失败我有一个共同的api从其他API获取不同的实体。下面是一个获取实体列表(Groovy)的方法。杰克逊映射作为参数

class CommonRestApi<T>{ 

CommonRestApi(){   
} 
.... 
List<T> getEntities(Class<T> clazz) { 
    ClientResponse response = some_rest_get //works fine 
    T[] entities 
    if (response.status == 200) { 
     try{ 
      GenericType<ResponseWrapper<T[]>> type = new GenericType<ResponseWrapper<T[]>>(){} //here is error 

      entities = response.getEntity(type).getData() 
     }catch(Exception e){ 
      log.debug e.getMessage() 
     } 
    } 
    else { 
     log.debug("Status Code: " + response.status) 
    } 
    return Arrays.asList(entities) 
} 
} 

ResponseWrapper此类类(JAVA):

public class ResponseWrapper<T> { 

private T data; 

public T getData() { 
    return data; 
} 

public void setData(T data) { 
    this.data = data; 
} 
} 

,并要求与方法:

commonRestApi.getEntities(MyDomain.class) 

这里的REST API返回的数据,但成功的映射到POJO不起作用。错误消息只是:null。任何人都可以告诉我,如果有可能的话。如果是,请给我一些指导。 注:通用的API类是常规

+0

您正尝试在新的GenericType >(){}中使用[super type token](http://gafter.blogspot.com/2006/12/super-type-tokens.html) ',但这只能用于具体的泛型类型参数。 'T'在哪里申报? – 2013-05-14 14:56:13

+0

我已添加类定义。请立即检查。 – Shafiul 2013-05-14 15:02:35

回答

-1

我认为这个问题是你不能实例化泛型的东西

new GenericType<ResponseWrapper<T[]>>(){} 

失败出于同样的原因是

new T[10]; 

会失败。 T类型被编译器完全擦除,并且在运行时不存在。

+0

-1不同之处在于,实例化一个'GenericType'不涉及数组的创建,这是'new T [10]'做的。 – 2013-05-14 14:49:58