同一類一個對象屬性賦值到另一個對象的屬性,前者存在的替換,不存在的不做改動

對於類

public class Car
{
private String brand;
private String color;
private Integer maxSpeed;
public Car()
{
    super();
}
public Car(String brand, String color, int maxSpeed)
{
    super();
    this.brand = brand;
    this.color = color;
    this.maxSpeed = maxSpeed;
}
public void introduce()
{
    System.out.println( "Car [brand=" + brand + ", color=" + color + ", maxSpeed=" + maxSpeed + "]");
}
public String getBrand()
{
    return brand;
}
public void setBrand(String brand)
{
    this.brand = brand;
}
public String getColor()
{
    return color;
}
public void setColor(String color)
{
    this.color = color;
}
public int getMaxSpeed()
{
    return maxSpeed;
}
public void setMaxSpeed(int maxSpeed)
{
    this.maxSpeed = maxSpeed;
}
@Override
public String toString()
{
    return "Car [brand=" + brand + ", color=" + color + ", maxSpeed=" + maxSpeed + "]";
}
}

用反射實現如:

public class CarToCar
{
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException
{
    Car car = new Car("瑪莎拉蒂", "紅", 200);
    Car oldCar = new Car("瑪莎拉蒂","黑",300);
    Field[] fields = Car.class.getDeclaredFields();
    for(Field field:fields){
        field.setAccessible(true);
        //System.out.println(field.getName());
        //System.out.println(field.get(car));
        if(null!=field.get(car)){
            field.set(oldCar, field.get(car));
        }
    }
    System.out.println(oldCar);
}

}
oldCar被替換。

發佈了23 篇原創文章 · 獲贊 20 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章