问题描述
我正在这样做:
Child child = (Child)parent;
这给了我一个错误,我发现不可能这样做.我不知道为什么,但是我认为应该可以,如果Child
类继承自Parent
类,则它包含Parent
对象数据.
Which gives me an error, I found it isn't possible to do it like this. I don't know exactly why, but I think it should be possible, if Child
class inherits from Parent
class, it contains the Parent
object data.
我的问题是:
- 为什么不起作用?
- 如何在不设置每个单亲父母的情况下完成这项工作这样的属性
- How can i make this work, without setting every single parent'sattribute like this
:
class Parent{
public int parameter1;//...
public int parameter1000;
}
class Child extends Parent
{
public Child(Parent parent)
{
this.parameter1 = parent.parameter1;//...
this.parameter1000 = parent.parameter1000;
}
}
推荐答案
好吧,你可以做一下:
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.
这篇关于如何在Java中将父项转换为子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!