對於類
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被替換。