2013-12-17 22 views
1

我想借代碼可以通過運行時解析的GenericType參數調用Java JAX-RS請求方法嗎?

WebTarget targetBase = ... 
targetBase.path("some_path").request(MEDIA_TYPE).get(new GenericType<List<MyModel>>(){}); 

,寫這樣的事情

public <T> T getViaRest(GenericType<T> myGenericType) { 
    return targetBase.path("some_path").request(MEDIA_TYPE).get(myGenericType); 
} 
... 
getViaRest(new GenericType<List<MyModel>>(){}); 
getViaRest(new GenericType<List<MyModel2>>(){}); 
... 

這樣我可以有我把我的自定義日誌記錄和錯誤處理代碼一般getViaRest方法,和它可以用於我所有的型號。

回答

0

如果您想爲客戶端添加日誌記錄,則應該使用客戶端請求filter來完成此操作。您可以通過Feature在客戶端註冊過濾器。

例子:

Client client = ClientBuilder.newClient().register(NEW_FEATURE); 

WebTarget targetBase = client.target("api"); 

targetBase.path("some_path").request(MEDIA_TYPE).get(new GenericType<List<MyModel>>(){}); 

的功能(你可以在它自己的階級提取出來):

private static final Feature NEW_FEATURE = new Feature() { 
    @Override 
    public boolean configure(FeatureContext context) { 
     context.register(new ClientRequestFilter() { 
      @Override 
      public void filter(ClientRequestContext requestContext) throws IOException { 
       //do your stuff here 
      } 
     }); 
     return true; 
    } 
}; 

您還可以添加不同的功能,這取決於你正在嘗試什麼做。

相關問題