I have an array of type Object in which I am saving object of different types, I want to cast them back their specific types after I take them out of the array. So when I take the PrintWriter object out I try PrintWriter(objArray[1][2]), but this does not work, how can I do this.
Downcasting is to be done as follows:
SubType instanceOfSubType = (SubType) instanceOfSuperType;
Thus, in your particular case you probably want to do this:
PrintWriter printWriter = (PrintWriter) objArray[1][2];
Also see "Casting Objects" chapter in Sun's tutorial about inheritance (scroll about half down).
That said, collecting everything in an opaque Object[] is not really ideal. If you can, just create a custom Javabean-like class with under each an encapsulated PrintWriter field. E.g.
public class MyBean {
private PrintWriter printWriter;
public void setPrintWriter(PrintWriter printWriter) {
this.printWriter = printWriter;
}
public PrintWriter getPrintWriter() {
return printWriter;
}
}
This way you can collect them in a List<MyBean> (to learn more about collections, check this Sun tutorial on the subject).
List<MyBean> myBeans = new ArrayList<MyBean>();
MyBean myBean1 = new MyBean();
myBean1.setPrintWriter(printWriter1);
myBeans.add(myBean1);
MyBean myBean2 = new MyBean();
myBean2.setPrintWriter(printWriter2);
myBeans.add(myBean2);
// ...
so that you can retrieve them as follows:
for (MyBean myBean : myBeans) {
PrintWriter printWriter = myBean.getPrintWriter();
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With