Java: Creating a subclass object from a parent object

前端 未结 11 2267
攒了一身酷
攒了一身酷 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:21

    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
                }
            }
        }
     }
    
    0 讨论(0)
  • 2020-12-09 15:21

    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.

    0 讨论(0)
  • 2020-12-09 15:23

    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 */
    
    0 讨论(0)
  • 2020-12-09 15:24

    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;
    }
    
    0 讨论(0)
  • 2020-12-09 15:32

    If you are using Spring in your project you may use ReflectionUtils.

    0 讨论(0)
提交回复
热议问题