2012-08-31 4 views
9

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 클래스의 인스턴스를 만들고 setter를 하나씩 호출하지 않고 상위 클래스의 모든 필드를 복사하는 방법이 있습니까?

나는이 일을하지 않습니다 또한

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

에서, Parent 사용자 정의 생성자가없는 나는 그것에 생성자를 추가 할 수 없습니다.

의견을 보내주십시오.

감사합니다.

+0

을 어떻게에서 부모의 getter 및 setter를 오버라이드 (override)에 대해 아이 클래스. Nambari가 제안한 것처럼. – km1

답변

0

필드를 비공개가 아닌 protected으로 설정하고 하위 클래스에서 직접 액세스 할 수 있습니다. 그게 도움이 되니?

+0

이 질문에 도움이되지 않을 것입니다. 부모의 다른 인스턴스에서 하위 인스턴스를 새로 만들어야합니다. – mavroprovato

0

부모를 허용하는 Child 생성자를 만들 수 있습니다. 그러나 거기에서 모든 값을 하나씩 설정해야합니다 (그러나 설정없이 자식 특성에 직접 액세스 할 수 있습니다).

리플렉션을 사용하면 해결 방법이 있지만 문제가 복잡해집니다. 일부 타이핑을 저장하기 만하면됩니다.

1

이렇게 반영 했습니까? 당신은 세터를 하나씩 불러 들였지만 당신은 그것들의 모든 이름을 알 필요가 없습니다.

15

시도해 보셨습니까?

BeanUtils.copyProperties 당신이 내가 그것을 할 반사를 사용하고 나를 위해 잘 작동 할 수

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

+0

답변 주셔서 감사합니다. 약간의 중재, 실제로 BeanUtils.copyProperties (부모, 자식) 또는 (소스 , 대상) – sheetal

+0

@sheetal Eh ... no. 그것은'BeanUtils.copyProperties (대상, 원본)'입니다 : https://github.com/apache/commons-beanutils/blob/f9ac36d916bf2271929b52e9b40d5cd8ea370d4b/src/main/java/org/apache/commons/beanutils/BeanUtils.java#L132 – Jasper

+0

@ 재 스퍼 나는 봄 프레임 워크를 사용하고 있다고 생각한다. 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 
      } 
     } 
    } 
} 
관련 문제