2011-11-15 50 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);

相关问题