I know downcasting is not doable. But I am trying to work around it.
This is what I have.
public class Ticket{
public int number;
public String description;
}
public class MyTicket extends Ticket{
public String status;
}
But in my app, I want to use the MyTicket class because I don’t want to force the original Ticket object to change. So when the Ticket object comes back from a call (webservice, DB, etc), I try to downcast to a MyTicket and it fails obviously.
MyTicket mt=(MyTicket)ws.getTicket(1234);
So I was trying to figure a way around this. I was thinking of writing a “copyAttributes” method or copy the attributes within the constructor of the MyTicket class, something like this:
MyTicket mt=new MyTicket(ws.getTicket(1234));
public class MyTicket extends Ticket {
public String status;
public MyTicket(Ticket tckt){
//copy tckt attributes to MyTicket attributes
}
}
Is there a way to get the attributes of a class and set them into another class?
Or is there a totally different way to downcast and I’m missing it?
*SOLUTION:*So I took the solution below and came up with this. I needed the change to return null if the main ticket is not found before the transfer happens:
public class MyTicket extends Ticket {
public String status;
public MyTicket(){}
public static MyTicket newInstance(Ticket tckt){
MyTicket mytkt=null;
if(tckt!=null){//copy tckt attributes to MyTicket attributes
BeanUtilsBean.getInstance().getConvertUtils().register(false,true,-1);
mytkt = new MyTicket();
BeanUtils.copyProperties(mytkt, tckt);
}
return mytkt;
}
}
I think you are doing right. If your object grows, you may want to use
Apache BeanUtilsto assist you in attrbute copying.