3

I'm new to dozer and I'm trying to create a map for ClassA and ClassB

public class ClassA {
    ClassC c;

    public ClassC getC() {
        return c;
    }
    public void setC(ClassC c) {
        this.c = c;
    }
}

public class ClassB {
    private String x;

    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
}


public abstract class ClassC {
    private String x;

    public String getX() {
        return x;
    }
    public void setX(String x) {
        this.x = x;
    }
}


public class ClassD extends ClassC {
}

I tried the mapping below

<mapping>
    <class-a>ClassA</class-a>
    <class-b>ClassB</class-b>

    <field>
        <a>c.x</a>
        <b>x</b>
    </field>
<mapping>

classC is an abstract class and ClassD is a concrete. When I map A->B there is no problem but when I map B->A, I'm getting InstantiationException. I suspect that the dozer is trying to instantiate abstract class classC. Any attribute to tell dozer to use ClassD? Please help.

[EDIT1] - Added the full class declaration.

jchips12
  • 1,177
  • 1
  • 11
  • 27

2 Answers2

1

This comment you've added is right on the money.

"classC is an abstract class and ClassD is a concrete. When I map A->B there is no problem but when I map B->A, I'm getting InstantiationException. I suspect that the dozer is trying to instantiate abstract class classC."

This is a bit of a shot in the dark, but what i would try, having read the dozer support pages and this question: How to map a field with type as an abstract class with dozer? . I might not be 100% right, but i'm pretty sure it's going to need to be something along these lines.

<mapping>
  <class-a>ClassA</class-a>
  <class-b>ClassB</class-b>

  <field>
    <a>c.x</a>
    <b>x</b>
    <a-hint>ClassD</a-hint>
  </field>
<mapping>
Community
  • 1
  • 1
M21B8
  • 1,867
  • 10
  • 20
  • Hi I've already tried it but its not working. If i'm correct c.x is a string so hint will not work. please see my answer. – jchips12 Jan 27 '14 at 11:00
  • Ok, no worries man. thanks for providing the solution, will try to remember this one for next time! – M21B8 Jan 27 '14 at 12:52
0

Ok got it. You need to use create-method

<mapping>
    <class-a create-method="ClassAFactory.createClassA">ClassA</class-a>
    <class-b>ClassB</class-b>

    <field>
        <a>c.x</a>
        <b>x</b>
    </field>
<mapping>

public class ClassAFactory {

    public static ClassA createClassA(){
        ClassA classA = new ClassA();
        classA.setC(new ClassD());
        return classA;
    }
}
jchips12
  • 1,177
  • 1
  • 11
  • 27