I have a requirement of copying data from one POJO to another. The 1st source POJO is in a JAR provided by 3rd party, the destination POJO is in my local project. The only difference between these two POJO is that the one in my local has an extra field compared to the one in the JAR.
The POJOs would look like this:
POJO from JAR:
class Demo {
private int no;
public int getNo(){
return this.no;
}
public void setNo(int no) {
this.no = no;
}
}
POJO in my project:
class AnotherDemo {
private int no;
private int lol;
public int getNo(){
return this.no;
}
public void setNo(int no) {
this.no = no;
}
public int getLol(){
return this.lol;
}
public void setLol(int lol) {
this.lol = lol;
}
}
I copied the contents of Demo to AnotherDemo, but when I try to access the data in AnotherDemo or try to set the fields in it, I get:
java.lang.ClassCastException: Demo cannot be cast to AnotherDemo
Main:
public class Main
{
public static void main(String[] args) {
Demo demo1 = new Demo();
Demo demo2 = new Demo();
demo1.setNo(1);
demo2.setNo(2);
List<Demo> demoList = new ArrayList<>();
demoList.add(demo1);
demoList.add(demo2);
List<AnotherDemo> anotherDemoList = new ArrayList(demoList);
anotherDemoList.forEach(ad -> {
System.out.println(ad.getNo()); // Code breaks here
// OR
ad.setLol(10); // Code breaks here too
});
}
}
I even tried using BeanUtils.copyProperties
, but the error remains the same when I try to get() or set().
Please note that copying contents with List<AnotherDemo> anotherDemoList = new ArrayList(demoList);
is existing code, it indeed copies the available content (field no in this case) and using an object mapper written to a JSON file.
Please suggest to me how I should copy from Demo to AnotherDemo and then set lol of AnotherDemo?