在 Java 中从其父类复制字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12217952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy fields from its parent class in Java
提问by Kevin
I have a question regarding Java class fields.
我有一个关于 Java 类字段的问题。
I have two Java classes: Parent and Child
我有两个 Java 类:Parent 和 Child
class Parent{
private int a;
private boolean b;
private long c;
// Setters and Getters
.....
}
class Child extends Parent {
private int d;
private float e;
// Setters and Getters
.....
}
Now I have an instance of the Parent
class. Is there any way to create an instance of the Child
class and copy all the fields of the parent class without calling the setters one by one?
现在我有一个Parent
类的实例。有没有什么方法可以创建Child
类的实例并复制父类的所有字段,而不需要一一调用setter?
I don't want to do this:
我不想这样做:
Child child = new Child();
child.setA(parent.getA());
child.setB(parent.getB());
......
Also, the Parent
does not have a custom constructor and I cannot add constructor onto it.
此外,Parent
它没有自定义构造函数,我无法在其上添加构造函数。
Please give you opinions.
请大家给点意见。
Many thanks.
非常感谢。
回答by mwikblom
Have you tried, using apache lib?
您是否尝试过使用 apache lib?
BeanUtils.copyProperties(child, parent)
http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html
http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html
回答by rcorbellini
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
}
}
}
}
回答by adrian
Did you try do this due reflection? Technicaly you invoke setters one by one but you don't need to know all names of them.
你有没有尝试做这个适当的反思?从技术上讲,您可以一一调用 setter,但您不需要知道它们的所有名称。
回答by pcalcao
You can set your fields as protected
instead of private and access them directly on the child class. Does that help?
您可以将您的字段设置protected
为私有,并直接在子类上访问它们。这有帮助吗?
回答by SJuan76
You can create a Child
constructor that accepts a Parent. But there, you will have to set all the values one by one (but you can access the Child attributes directly, without set).
您可以创建一个Child
接受 Parent的构造函数。但是在那里,您必须一一设置所有值(但您可以直接访问 Child 属性,无需设置)。
There is a workaround with reflection, but it only adds complication to this. You don't want it just for save some typing.
有一种使用反射的解决方法,但这只会增加复杂性。你不想要它只是为了节省一些打字。