Java: Creating a subclass object from a parent object

前端 未结 11 2309
攒了一身酷
攒了一身酷 2020-12-09 14:28

Newbie Java question. Say I have:

public class Car{
  ...
}

public class Truck extends Car{
  ...
}

Suppose I already have a Car object, h

11条回答
  •  执念已碎
    2020-12-09 15:07

    Would I have to write my own copy constructor? This would have to be updated everytime Car gets a new field...

    Not at all!

    Try this way:

    public class Car{
        ...
    }
    
    public class Truck extends Car{
        ...
    
        public Truck(Car car){
            copyFields(car, this);
        }
    }
    
    
    public static void copyFields(Object source, Object target) {
            Field[] fieldsSource = source.getClass().getFields();
            Field[] fieldsTarget = target.getClass().getFields();
    
            for (Field fieldTarget : fieldsTarget)
            {
                for (Field fieldSource : fieldsSource)
                {
                    if (fieldTarget.getName().equals(fieldSource.getName()))
                    {
                        try
                        {
                            fieldTarget.set(target, fieldSource.get(source));
                        }
                        catch (SecurityException e)
                        {
                        }
                        catch (IllegalArgumentException e)
                        {
                        }
                        catch (IllegalAccessException e)
                        {
                        }
                        break;
                    }
                }
            }
        }
    

提交回复
热议问题