Search code examples
javaserializationpojo

Copy a model object in java


What is the best way if I want to copy a model object in java. Because writing copy() function for a nested object in java becomes a lot of works. I just want to avoid that. As a shortcut I use this approach.

    public static <T> T copy(T model, Class<T> tClass) throws Exception {
        final ObjectMapper objectMapper = new ObjectMapper();
        final byte[] bytes = objectMapper.writeValueAsBytes(model);
        final T copy = objectMapper.readValue(bytes, tClass);
        return copy;
    }

And use it like this.

    final McTrack copy = copy(new McTrack(), McTrack.class);

I have made a Utility function copy() that takes a model object and returns a copy of that. First I serialize the entire object into json and then deserialize it again to make a copy. But I am not sure it really efficient. Is there any better way to copy plain old java objects.


Solution

  • You can also use Dozer library: http://dozer.sourceforge.net/

    You can easily copy whole POJOs from one to another like this:

    Mapper mapper = new DozerBeanMapper();
    DestinationObject destObject = mapper.map(sourceObject, DestinationObject.class);
    

    What is really usufull you can configure your own mappings like this:

    <mapping>
      <class-a>yourpackage.yourSourceClassName</class-a>
      <class-b>yourpackage.yourDestinationClassName</class-b>
        <field>
          <a>yourSourceFieldName</a>
          <b>yourDestinationFieldName</b>
        </field>
    </mapping> 
    

    Additionally you can use different Technics to copy object, use custom factories, special getters/setters and a lot useful things: http://dozer.sourceforge.net/documentation/mappings.html