对于类
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被替换。
本文介绍了一个使用Java反射机制来更新一个对象的属性值到另一个对象的示例。通过获取类的所有声明字段并设置其可访问性,可以将源对象的属性值复制到目标对象对应的属性中。
1400

被折叠的 条评论
为什么被折叠?



