且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中将父项转换为子项

更新时间:2023-01-12 17:46:49

好吧,你可以做一下:

Parent p = new Child();
// do whatever
Child c = (Child)p;

或者,如果您必须从纯父对象开始,则可以考虑在父类中包含一个构造函数并调用:

Or if you have to start with a pure Parent object you could consider having a constructor in your parent class and calling :

class Child{
    public Child(Parent p){
        super(p);
    }
}
class Parent{
    public Parent(Args...){
        //set params
    }
}

或构图模型:

class Child {
    Parent p;
    int param1;
    int param2;
}

在这种情况下,您可以直接设置父级.

You can directly set the parent in that case.

您还可以使用Apache Commons BeanUtils执行此操作.使用其BeanUtils类,您可以访问许多通过反射来填充JavaBeans属性的实用程序方法.

You can also use Apache Commons BeanUtils to do this. Using its BeanUtils class you have access to a lot of utility methods for populating JavaBeans properties via reflection.

要将所有公共/继承的属性从父对象复制到子类对象,可以使用其静态copyProperties()方法:

To copy all the common/inherited properties from a parent object to a child class object you can use its static copyProperties() method as:

BeanUtils.copyProperties(parentObj,childObject);

但是请注意,这是一项繁重的操作.

Note however that this is a heavy operation.