java - 使用 .getClass() 时如何将参数传递给构造函数?

标签 java reflection jackson spring-remoting

我有这行代码,它在该版本上工作:

...
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.classnew Wrapper().getClass()new Wrapper(theParam).getClass() 返回相同的值:Wrapper.class。如果您有合适的构造函数,即能够获取参数 theParam 的构造函数,那么所有这一切都可以实现。在您的情况下,类 Wrapper 没有接受 Class 类型参数的构造函数,因此它会提示这一点。

关于java - 使用 .getClass() 时如何将参数传递给构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8133969/

相关文章:

java - 使用 Jackson Json 将对象序列化为字符串后日期发生变化

scala - 如何在反序列化期间初始化 transient 字段?

java - 如何反序列化 Map<String, Object> 使用不同类型的不同 key 与 jackson ?

java - 需要在for循环中声明变量

java - hibernate查询多个对象选择

java - 使用 uid 显示当前用户实时数据库中的某些数据

android - 在 Android 库 Java 中使用用户定义的方法

java - Enum 实现 lambda 可能接口(interface)的简写符号

c# - 比较两个集合

c# - Lazy<T> 实现和 .NET 泛型