Pregunta

I have two POJO with same setter and getter now i want to copy all the bean value to another bean. What can be the best way to copy all the information of one POJO to another.?

¿Fue útil?

Solución

U can use Apache BeanUtils ...

Otros consejos

That's the perfect situation to use a Java Bean mapper like orika or Dozer. They can automate this task pretty well and you can avoid a lot of code.

You can basically copy all properties of random classes to other classes if they have the correct getters and setters with just a single line.

Implement deep copy here. It will be best as all sub POJO's inside POJO will also be copied and there will be no loss.

public CloneExample deepCopy() {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            return (CloneExample) ois.readObject();
        } catch (IOException e) {
            return null;
        } catch (ClassNotFoundException e) {
            return null;
        }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top