Translate

Thursday, April 23, 2015

Java copy one object to another

You could use the copyProperties method in the org.apache.commons.beanutils.BeanUtilsBean class to copy properties by name from one class to another. If some property name doesn't match, it simply ignores that property.

In the example below I am copying properties of Ferrari into Toyota.


Main Program


package com.company;

import org.apache.commons.beanutils.BeanUtilsBean;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

public class Main {


    public static void main(String[] args) throws IOException, InvocationTargetException, IllegalAccessException {
        Ferrari ferrari = new Ferrari();
        ferrari.setColor("red");
        ferrari.setHorsePower(300);

        Toyota toyota = new Toyota();

        BeanUtilsBean beanUtilsBean = new BeanUtilsBean();
        beanUtilsBean.copyProperties(toyota, ferrari);//copy ferrari into toyota
        System.out.println(toyota.getColor());//red
        System.out.println(toyota.getHorsePower());//300
    }

}


Ferrari class


package com.company;

public class Ferrari {

    private int HorsePower;
    private String Color;
    private int mileage;

    public int getHorsePower() {
        return HorsePower;
    }

    public void setHorsePower(int horsePower) {
        HorsePower = horsePower;
    }

    public String getColor() {
        return Color;
    }

    public void setColor(String color) {
        Color = color;
    }

    public int getMileage() {
        return mileage;
    }

    public void setMileage(int mileage) {
        this.mileage = mileage;
    }
}

Toyota class


package com.company;

public class Toyota{

    private int HorsePower;
    private String Color;
    private String useLess="";

    public int getHorsePower() {
        return HorsePower;
    }

    public void setHorsePower(int horsePower) {
        HorsePower = horsePower;
    }

    public String getColor() {
        return Color;
    }

    public void setColor(String color) {
        Color = color;
    }

    public String getUseLess() {
        return useLess;
    }

    public void setUseLess(String useLess) {
        this.useLess = useLess;
    }
}

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator