![](/img/trans.png)
[英]How to pass a configurable parameter to the constructor when using a Provider?
[英]How to pass parameter to constructor when using .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: org.apache.commons.httpclient.AutoCloseInputStream@ef9e8eb; 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: org.apache.commons.httpclient.AutoCloseInputStream@ef9e8eb; line: 1, column: 3]
如何將參數發送到將獲得其值的類的對象?
Wrapper.class
和new Wrapper().getClass()
和new Wrapper(theParam).getClass()
返回相同的值: Wrapper.class
。 如果您有可構造的構造函數,即能夠獲取參數theParam
構造函數,則所有這theParam
。 在您的情況下,類Wrapper
沒有接受Class
類型參數的構造函數,因此它對此有所抱怨。
我假設您需要的是指示供Jackson使用的通用包裝類型。 有幾種方法可以做到這一點:
Wrapper<Model> value = objectMapper.readValue(source, new TypeReference<Wrapper<Model>>() { });
Wrapper<Model> value = objectMapper.readValue(source, objectMapper.getTypeFactory().constructParametricType(Wrapper.class, Model.class);
我不確定TypeReference或JavaType(它們是通過類框架傳遞Class實例(經過類型擦除,即沒有泛型!)的啟用泛型的替代方法)的方式,但我認為應該可行。
另外,如果無法正常工作,請嘗試對Wrapper進行子類化-具體的子類WILL實際上具有必要的信息:
公共類ModelWrapper擴展了包裝器{} ModelWrapper包裝= restTemplate.getForObject(BASE_URL,ModelWrapper.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.