同一类一个对象属性赋值到另一个对象的属性,前者存在的替换,不存在的不做改动

    xiaoxiao2021-03-25  163

    对于类

    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被替换。

    转载请注明原文地址: https://ju.6miu.com/read-1393.html

    最新回复(0)