2012-08-31 42 views
9

我有一个关于Java类字段的问题。在Java中从其父类复制字段

我有两个Java类:父母与子女

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

现在我有Parent类的一个实例。有什么办法可以创建一个Child类的实例,并复制父类的所有字段而无需逐个调用setters?

我不想这样做:

Child child = new Child(); 
    child.setA(parent.getA()); 
    child.setB(parent.getB()); 
    ...... 

此外,Parent没有一个自定义的构造函数,我不能添加到构造它。

请给你的意见。

非常感谢。

+0

如何覆盖在父母的getter和setter儿童班。像Nambari所说的那样。 – km1

回答

0

你可以设置你的领域protected而不是私人和直接访问它们的子类。这有帮助吗?

+0

这不会帮助,从这个问题看来他需要从家长的另一个实例创建儿童的新实例 – mavroprovato

0

您可以创建一个Child构造函数接受父。但是在那里,你将不得不逐个设置所有的值(但是你可以直接访问子属性,没有设置)。

有与反思的解决办法,但它只会增加复杂性这一点。 你不希望它只是为了节省一些打字。

1

你尝试这样做,由于反射?技术你可以一个接一个地调用setters,但你不需要知道它们的全部名字。

15

你试过了吗?

BeanUtils.copyProperties(子女,父母)

http://commons.apache.org/beanutils/apidocs/org/apache/commons/beanutils/BeanUtils.html

+0

感谢您的回答。一个小corection,它实际上BeanUtils.copyProperties(父母,子女)或(源,目标) – sheetal

+0

@sheetal Eh ...没有。它是'BeanUtils.copyProperties(destination,original)':https://github.com/apache/commons-beanutils/blob/f9ac36d916bf2271929b52e9b40d5cd8ea370d4b/src/main/java/org/apache/commons/beanutils/BeanUtils.java#L132 – Jasper

+0

@Jasper我想我正在使用spring框架,然后https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/BeanUtils.html – sheetal

4

你可以使用反射我做到这一点,我很好地工作:

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 
      } 
     } 
    } 
} 
相关问题