简体   繁体   中英

Java: Creating a subclass object from a parent object

Newbie Java question. Say I have:

public class Car{
  ...
}

public class Truck extends Car{
  ...
}

Suppose I already have a Car object, how do I create a new Truck object from this Car object, so that all the values of the Car object is copied into my new Truck object? Ideally I could do something like this:

Car c = new Car();
/* ... c gets populated */

Truck t = new Truck(c);
/* would like t to have all of c's values */

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

Yes, just add a constructor to Truck. You will probably want to add a constructor to Car also, though not necessarily public:

public class Car {
    protected Car(Car orig) {
    ...
}

public class Truck extends Car {
    public Truck(Car orig) {
        super(orig);
    }
    ...
}

As a rule it's generally best to make classes either leaf (and you might want to mark those final) or abstract.

It looks as if you want a Car object, and then have the same instance turn into a Truck . A better way of doing this is to delegate behaviour to another object within Car ( Vehicle ). So:

public final class Vehicle {
    private VehicleBehaviour behaviour = VehicleBehaviour.CAR;

    public void becomeTruck() {
        this.behaviour =  VehicleBehaviour.TRUCK;
    } 
    ...
}

If you implement Cloneable then you can "automatically" copy an object to a instance of the same class. However there are a number of problems with that, including having to copy each field of mutable objects which is error-prone and prohibits the use of final.

如果您在项目中使用 Spring,则可以使用 ReflectionUtils。

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;
                }
            }
        }
    }

Yes, you have to do this manually. You'll also need to decide how "deeply" to copy things. For instance, suppose the Car has a collection of tyres - you could do a shallow copy of the collection (such that if the original object changes the contents of its collection, the new object would see the change too) or you could do a deep copy which created a new collection.

(This is where immutable types like String often come in handy - there's no need to clone them; you can just copy the reference and know that the contents of the object won't change.)

you can use reflection i do it and work fine for me:

public Child(Parent parent){
    for (Method getMethod : parent.getClass().getMethods()) {
        if (getMethod.getName().startsWith("get")) {
            try {
                Method setMethod = this.getClass().getMethod(getMethod.getName().replace("get", "set"), getMethod.getReturnType());
                setMethod.invoke(this, getMethod.invoke(parent, (Object[]) null));

            } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                //not found set
            }
        }
    }
 }

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

Essentially, yes - you can't just convert an object in Java.

Fortunately you don't have to write all the code yourself - look into commons-beanutils , specifically methods like cloneBean . This has the added advantage that you don't have to update it every time it gets a new field!

You could always use a mapping Framework such as Dozer . By default (without further configuration ), it maps all fields of the same name from one object to another using the getter and setter methods.

Dependency:

<dependency>
    <groupId>net.sf.dozer</groupId>
    <artifactId>dozer</artifactId>
    <version>5.5.1</version>
</dependency>

Code:

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

// ...

Car c = new Car();
/* ... c gets populated */

Truck t = new Truck();
Mapper mapper = new DozerBeanMapper();
mapper.map(c, t);
/* would like t to have all of c's values */

The solutions presented above have limitations you should be aware of. Here's a short summary of algorithms for copying fields from one class to another.

  • Tom Hawtin : Use this if your superclass has a copy constructor. If it does not you will need a different solution.
  • Christian : Use this if the superclass does not extend any other class. This method does not copy fields recursively upwards.
  • Sean Patrick Floyd : This is a generic solution for copying all fields recursively upwards. Be sure to read @jett's comment that a single line must be added to prevent an endless loop.

I reproduce Sean Patrick Floyd's analyze function with the missing statement:

private static Map<String, Field> analyze(Object object) {
    if (object == null) throw new NullPointerException();

    Map<String, Field> map = new TreeMap<String, Field>();

    Class<?> current = object.getClass();
    while (current != Object.class) {
        Field[] declaredFields = current.getDeclaredFields();
        for (Field field : declaredFields) {
            if (!Modifier.isStatic(field.getModifiers())) {
                if (!map.containsKey(field.getName())) {
                    map.put(field.getName(), field);
                }
            }
        }

        current = current.getSuperclass();   /* The missing statement */
    }
    return map;
}

I know this is an OLD question, but I hate to leave out dated answers when things have improved.

Using JSON is much easier. Convert it to JSON and back again as child.

Here is an Android Kotlin Example.

    val gson = Gson()    
    val childClass = gson.fromJson(
        gson.toJson(parentObject), 
        object: TypeToken<ChildObject>(){}.type
    ) as ChildObject

I think in Java it would be basically.

Gson gson = new Gson()
ChildObject child = (ChildObject) gson.fromJson(
    gson.toJson(parentObject),
    TypeToken<ChildObject>(){}.getType()
) 

And you're done, no messiness, just simple json in, json out. If you don't have gson, I'm sure you have other json options available to you.

It's a WHOLE lot cleaner and faster than doing reflection and all that craziness.

您将需要一个复制构造函数,但您的复制构造函数可以使用反射来查找两个对象之间的公共字段,从“原型”对象中获取它们的值,并将它们设置在子对象上。

You could use the reflection API to loop through each of the Car fields and assign the value to the equivalent Truck fields. This can be done within truck. Further it is the only way to access the private fields of Car - at least in an automatic sense, providing that a security manager is not in place and restricting access to private field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM