create a common converter for objects from different packages

后端 未结 4 1411
温柔的废话
温柔的废话 2021-01-06 06:03

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.         


        
4条回答
  •  伪装坚强ぢ
    2021-01-06 06:18

    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.

提交回复
热议问题