Dozer can map an object to other as long as it finds attributes of the same name in both classes. But in case, if the data types of mapped attributes are different, Dozer will perform automatic type conversion wherever it is possible.
Let’s see it with an example.
Type2.java
package com.sample.app.model;
public class Type2 {
private int a;
private int b;
public Type2() {
}
public Type2(int a, int b) {
this.a = a;
this.b = b;
}
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
@Override
public String toString() {
return "Type2 [a=" + a + ", b=" + b + "]";
}
}
Type3.java
package com.sample.app.model;
public class Type3 {
private String a;
private double b;
public Type3() {
}
public Type3(String a, double b) {
this.a = a;
this.b = b;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
@Override
public String toString() {
return "Type3 [a=" + a + ", b=" + b + "]";
}
}
DataTypeConversionDemo.java
package com.sample.app;
import org.dozer.DozerBeanMapper;
import com.sample.app.model.Type2;
import com.sample.app.model.Type3;
public class DataTypeConversionDemo {
public static void main(String[] args) {
DozerBeanMapper mapper = new DozerBeanMapper();
Type3 type3 = new Type3("10", 20.987);
Type2 type2 = mapper.map(type3, Type2.class);
System.out.println(type3);
System.out.println(type2);
}
}
Output
Type3 [a=10, b=20.987] Type2 [a=10, b=20]
As you observe the code, the attribute names are the same but their data types are different.
In the Type2 class, a, b are of type int and in Type3 class, 'a' is of type String and 'b' is of type double.
No comments:
Post a Comment