如何将Java对象(bean)转换为键值对(反之亦然)?

说我有一个非常简单的java对象,它仅具有一些getXXX和setXXX属性。该对象仅用于处理值,基本上是记录或类型安全(和性能)映射。我经常需要将此对象转换为键值对(字符串或类型安全)或从键值对转换为该对象。


除了反射或手动编写代码以进行此转换之外,实现此目的的最佳方法是什么?


一个示例可能是通过jms发送此对象,而不使用ObjectMessage类型(或将传入消息转换为正确的对象)。

如何将Java对象(bean)转换为键值对(反之亦然)?

慕田峪4524236
浏览 1668回答 4
4回答

偶然的你

总是有apache commons beanutils,但是当然它在后台使用了反射

慕容森

许多潜在的解决方案,但让我们再添加一个。使用Jackson(JSON处理库)进行“无json”转换,例如:ObjectMapper m = new ObjectMapper();Map<String,Object> props = m.convertValue(myBean, Map.class);MyBean anotherBean = m.convertValue(props, MyBean.class);(此博客条目有更多示例)您基本上可以转换任何兼容的类型:兼容的意思是,如果您确实从类型转换为JSON,并且从该JSON转换为结果类型,则条目将匹配(如果配置正确,也可以忽略无法识别的类型)。对于可能发生的情况,包括Maps,Lists,数组,基元和类bean POJO,效果很好。

慕哥9229398

这是一种将Java对象转换为Map的方法public static Map<String, Object> ConvertObjectToMap(Object obj) throws&nbsp;&nbsp; &nbsp; IllegalAccessException,&nbsp;&nbsp; &nbsp; IllegalArgumentException,&nbsp;&nbsp; &nbsp; InvocationTargetException {&nbsp; &nbsp; &nbsp; &nbsp; Class<?> pomclass = obj.getClass();&nbsp; &nbsp; &nbsp; &nbsp; pomclass = obj.getClass();&nbsp; &nbsp; &nbsp; &nbsp; Method[] methods = obj.getClass().getMethods();&nbsp; &nbsp; &nbsp; &nbsp; Map<String, Object> map = new HashMap<String, Object>();&nbsp; &nbsp; &nbsp; &nbsp; for (Method m : methods) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (m.getName().startsWith("get") && !m.getName().startsWith("getClass")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object value = (Object) m.invoke(obj);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map.put(m.getName().substring(3), (Object) value);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; return map;}这是怎么称呼的&nbsp; &nbsp;Test test = new Test()&nbsp; &nbsp;Map<String, Object> map = ConvertObjectToMap(test);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java