0

What's the best way to copy one Java object of a class to another object of the same class? I tried BeanUtil.copyProperties but it didn't work for some reason. The class is a complex class. (class contains another class objects etc)

My aim is to populate values in order through hibernate function

Public Response getOrder(Order order, Ticket ticket) {

order = OrderManager.getOrderByTicket(ticket); //Hibernate function This doesn't work, order object gets a new reference

}

Tried doing this

Public Response getOrder(Order order, Ticket ticket) {

Order temp = OrderManager.getOrderbByTicket(ticket);

//Now I want to copy temp to order

}
BrownTownCoder
  • 1,312
  • 5
  • 19
  • 25
  • You should provide more information and/or some example code - or a stacktrace if you get an exception so that we can better help you figure out your problem. – cjstehno Apr 24 '14 at 20:38

5 Answers5

1

If all the fields are serializable then you can use ObjectOutputStream and ObjectInputStream.

If You need special handling during the serialization and deserialization process then implement special methods writeObject() and readObject().

Please have a look at IO: Custom Reading and Writing with Serializable .


Sample code:

    class MyClass implements Serializable {
        private static final long serialVersionUID = 1L;
        String str;
        List<Integer> list = new ArrayList<Integer>();

        public MyClass(String str) {
            this.str = str;
        }
    }

    MyClass obj1 = new MyClass("abc");
    obj1.list.add(1);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(buffer);
    oos.writeObject(obj1);
    oos.close();

    byte[] rawData = buffer.toByteArray();
    ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(rawData));
    MyClass obj2 = (MyClass) ois.readObject();

    System.out.println(obj2.str);
    System.out.println(obj2.list.get(0));
Braj
  • 46,415
  • 5
  • 60
  • 76
1

To do a deep copy using Serialize / DeSerialize, you can use the code like below,

public Object deepCopy(Object input) {

    Object output = null;
    try {
        // Writes the object
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(input);

        // Reads the object
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        output = objectInputStream.readObject();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return output;
}
Jay
  • 9,189
  • 12
  • 56
  • 96
  • The problem is I am passing an object through 5 functions and want to assign the values using hibernate. When I do obj = getObj(), it loses it's pass by reference and the changes are not reflected back to the main function. I am trying to do a temp = getObj() and try and copy values from temp to obj. I don't think your example would work, as I will be back at square one if I use obj = deepCopy (temp) – BrownTownCoder Apr 24 '14 at 20:52
  • Don't worry about pass by reference pass by value and all. This is a code used in Hibernate environment and it just do a copy for the given object along with all children (read from the DB and can be used to insert again as a new set of records). – Jay Apr 24 '14 at 20:55
0

I suppose you could use reflection if it was REALLY important or time consuming, but as I see it, there are two main choices

  • One If you have access to the class, just implement Clonable and have the clone method produce a deep copy of the object and all its subobjects.

  • Two Code it by hand. It may be time consuming and boring, but it works in all cases.

Johm Don
  • 609
  • 2
  • 5
  • 15
0

I believe you are talking about a 'deep' copy.

A similar question and various solutions are detailed here:

How do you make a deep copy of an object in Java?

The easiest way seems to be serialising the object and then deserialising it.

Community
  • 1
  • 1
GoldenJam
  • 1,459
  • 1
  • 11
  • 17
0

Better do it like this:

Public Response getOrder(Request request) {

Order temp = OrderManager.getOrderbByTicket(request.getTicket());
request.setOrder(temp);


//process the response

}

This will solve the problem of getting back the Order to the caller of the function. If you want that the caller gets a deep copy than serialize and deserialize it before seting it to the request

Alex
  • 54
  • 3
  • The problem is I am passing an object through 5 functions and want to assign the values using hibernate. When I do obj = getObj(), it loses it's pass by reference and the changes are not reflected back to the main function. I am trying to do a temp = getObj() and try and copy values from temp to obj. I don't think your example would work, as I will be back at square one if I use obj = deepCopy (temp) – BrownTownCoder Apr 24 '14 at 20:54
  • To be honest I don't 100% understand your question. You want to preserve the reference but also want a copy of the whole graph (you wrote the object is complex, so I assumed more levels). Can you post some example so that it gets more clear? Assigning the values by Hibernate you mean, Hibernate will populate them, right? After that you want to stay attached to the session or not? – Alex Apr 24 '14 at 21:05
  • getOrder has 2 params but you pass only one? – Alex Apr 24 '14 at 21:09
  • ah ok, now I start to understand, you want to return a response and modify the parameter reference. I think this is not possible. You should pack it into a container object like Response.setTicket(Ticket ticket) or if it is not possible, the make a Request Class with attributes ticket and order and then: request.setOrder(OrderManager.getOrder(request.getTicket())) – Alex Apr 24 '14 at 21:16