2012-08-31 46 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 
      } 
     } 
    } 
} 
相關問題