为不同软件包中的对象创建一个通用转换器 [英] create a common converter for objects from different packages

查看:72
本文介绍了为不同软件包中的对象创建一个通用转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有5个Web服务,A,B,C,D和E.每个都有自动生成完全相同结构的对象,但名称不同,包装不同。

  com.ws.a.carA包含参数和com.ws.a.wheelA 
com.ws.b.carB包含参数和com.ws.b.wheelB
com.ws.c.carC包含参数和com.ws.c.wheelC
com.ws.d.carD包含参数和com.ws.d.wheelD
com.ws. e.carE包含参数和com.ws.e.wheelE

我想要创建一个函数可以将这些对象(和内层轮)转换为一个名为

  com.model的对象。汽车,

但是我不想像许多功能:

  com.model.car convert(com.ws.a.objA obj)
com.model.car convert(com.ws.b.objB obj )

...



问题是的,我不能给所有的对象一个通用接口impl因为我不想手动更改自动生成的类(它们会经常重新创建)。



我需要一种方法,可能使用泛型来创建通用函数

  com.model.car convert(T obj)

适用于所有类型的汽车,但我不知道如何实现。

解决方案

你可以为此使用反射。最简单和最干净的方法可能是使用 Apache Common BeanUtil ,或者 PropertyUtils#copyProperties BeanUtils#copyProperties



PropertyUtils#copyProperties将值从一个对象复制到另一个字段名称相同。因此,对于copyProperties(dest,orig),它会为两个对象中存在的所有字段调用dest.setFoo(orig.getFoo())。

BeanUtils#copyProperties执行相同,但您可以注册转换器,以便在必要时将值从字符串转换为诠释。有很多标准转换器,但你可以注册你自己的,在你的情况com.ws.a.wheelA com.model.wheel,或任何。


I have 5 webservices, A, B, C, D, and E. Each has autogenerated objects of the exact same structure, but with different names and in different packages.

com.ws.a.carA contains  parameters and com.ws.a.wheelA
com.ws.b.carB contains  parameters and com.ws.b.wheelB
com.ws.c.carC contains  parameters and com.ws.c.wheelC
com.ws.d.carD contains  parameters and com.ws.d.wheelD
com.ws.e.carE contains  parameters and com.ws.e.wheelE

I want to create one function that can convert each of these objects (and the inner wheel) to a object named

com.model.car,

but I dont wan't many functions like :

com.model.car convert(com.ws.a.objA obj)
com.model.car convert(com.ws.b.objB obj)

...

The problem is, I can't give all the objects a common interface to implement, because I don't want to manually change the autogenerated classes (they are recreated frequently).

I need a way, probably with generics, to create a common function

com.model.car convert(T obj)

that will work for all the car types but I'm not sure how to implement it.

解决方案

You can use reflection for this. The easiest and cleanest way would probably be to use Apache Common BeanUtils, either PropertyUtils#copyProperties or BeanUtils#copyProperties.

PropertyUtils#copyProperties copies the values from one object to another, where the field names are the same. So with copyProperties(dest, orig), it calls dest.setFoo(orig.getFoo()) for all fields which exist in both objects.

BeanUtils#copyProperties does the same, but you can register converters so that the values get converted from String to Int, if necessary. There are a number of standard converters, but you can register your own, in your case com.ws.a.wheelA to com.model.wheel, or whatever.

这篇关于为不同软件包中的对象创建一个通用转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆