2016-09-05 2 views
0

두 개의 매우 유사한 클래스 (많은 변수를 공유하고 있습니다)를 하나씩 가지고 싶습니다. 다음과 같이 단순화 :다른 자식에게 부모와 자녀를 캐스팅하십시오.

abstract class AbstractPreferred 
{ 
    public boolean a; 
    public int  b; 
    /* ... */ 
    public float  z; 
    /* ... */ 
    /* getters and setters */ 
} 
class ClassForJacksonDatabind extends AbstractPreferred 
{ 
    public HashMap<String,Double> different; 
    /* getter and setter for different */ 
    public Preferred toPreferred() 
    { 
     Preferred p = (AbstractPreferred) this; 
     p->convertDifferent(this.different); 
     return p; 
    } 
} 
class Preferred extends AbstractPreferred 
{ 
    protected HashMap<Integer,Double> different; 
    /* getters and setters */ 
    public void convertDifferent(HashMap<String,Double> d) 
    { 
     /* conversion */ 
    } 
} 

을하지만, 분명히 그것은 작동하지 않습니다

class ClassForJacksonDatabind 
{ 
    public boolean a; 
    public int  b; 
    /* ... */ 
    public float  z; 
    /* ... */ 
    public HashMap<String,Double> different; 
} 
class Preferred 
{ 
    protected boolean a; 
    protected int  b; 
    /* ... */ 
    protected float  z; 
    /* ... */ 
    protected HashMap<Integer,Double> different; 
    /* getters and setters */ 
} 

내가 수동으로 모든 단일 공유 변수를 복사하지 않으려하기 때문에, 나는이 아이디어를 내놓았다. 그럴 수있는 방법이 있습니까? 내 주요 목표는 다음과 같이 뭔가를해야하는 피할 수있다 :

public Preferred toPreferred() 
{ 
    Preferred p = new Preffered(); 
    p.setA(this.a); 
    p.setB(this.b); 
    /* ... */ 
    p.setZ(this.z); 
    p.setAa(this.aa); 
    /* ... */ 
    p.setZz(this.zz); 
    p.convertDifferent(this.different); 
} 

또는

public Preferred toPreferred() 
{ 
    Preferred p = new Preferred(this); 
    p.convertDifferent(this.different); 
} 
/* ... */ 
Preferred(AbstractPreferred other) 
{ 
    this.a = other.a; 
    this.b = other.b; 
    /* ... */ 
    this.zz = other.zz; 
} 

ClassForJacksonDatabind의 구조는 I로까지 (외부 JSON 파일에서 파생됩니다, 그래서 그것을 변경할 수 없습니다 알아, 어쨌든).

+0

한 클래스에서 다른 클래스로 변환하는 방법으로 유틸리티 클래스를 만들 수 있습니다. 두 클래스 사이에 어떤 관계가 있습니까? – Slimu

+0

실제로 변환이 필요한가요? 기본 HashMap 구조체에 View를 제공하여 HashMap 인터페이스를 모방하는 컴포지션을 사용하는 것을 상상해보십시오. – Fildor

+0

@Fildor 해당 변환의 주 목적은 이후 단계의 메모리를 확보하는 것입니다. 프로그램의 예를 들어 정수 키는 문자열 키보다 훨씬 적은 메모리를 차지합니다. 변환 후 오래된 개체는 가비지 수집되어 프로그램의 집중적 인 부분에 대한 작업 메모리를 확보합니다. – joelproko

답변

1

Dozer과 같이 Object to Object 매핑을위한 라이브러리가 많이 있습니다. 정말로 바퀴를 재발 명하고 자신의 매퍼를 만드시겠습니까?

+0

니스, 고마워. :디 – joelproko

관련 문제