2011-11-15 48 views
0

我有一個行代碼,並將其在該版本的工作:如何在使用.getClass()時將參數傳遞給構造函數?

... 
Wrapper<Model> wrapped = restTemplate.getForObject(BASE_URL, Wrapper.class, map); 
... 

不過,我想送參數的構造函數:

... 
Wrapper<Model> wrapped = restTemplate.getForObject(BASE_URL, new Wrapper(Model.class).getClass(), map); 
... 

這引發了我的異常:

org.springframework.web.client.ResourceAccessException: I/O error: No suitable constructor found for type [simple type, class a.b.c.d.model.Wrapper]: can not instantiate from JSON object (need to add/enable type information?) 
at [Source: [email protected]; line: 1, column: 3]; nested exception is org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class a.b.c.d.model.Wrapper]: can not instantiate from JSON object (need to add/enable type information?) 
at [Source: [email protected]; line: 1, column: 3] 

如何將參數發送給一個對象,我將獲得它的類的值?

+0

'Wrapper'是什麼類?這是? - > http://download.oracle.com/javase/6/docs/api/java/sql/Wrapper.html –

回答

1

Wrapper.classnew Wrapper().getClass()new Wrapper(theParam).getClass()返回相同的值:Wrapper.class。所有這些如果你有可變的構造函數,即構造函數能夠得到參數theParam。在你的案例類Wrapper沒有接受類型爲Class的參數的構造函數,所以它抱怨這一點。

0

我假設你需要的是指出傑克遜使用的Wrapper的泛型類型。有幾個方法可以做到這一點:

Wrapper<Model> value = objectMapper.readValue(source, new TypeReference<Wrapper<Model>>() { }); 
Wrapper<Model> value = objectMapper.readValue(source, objectMapper.getTypeFactory().constructParametricType(Wrapper.class, Model.class); 

我不知道如何要麼TypeReference或java類型(其替代傳遞類實例(即是類型擦除啓用泛型,即沒有仿製藥)!)通過Spring框架,但我認爲它應該是可能的。

或者,如果不能進行工作,嘗試子類包裝 - 具體子類,實際上有必要信息:

公共類ModelWrapper擴展包裝{} ModelWrapper包裹= restTemplate。 getForObject(BASE_URL,ModelWrapper.class);

相關問題