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.
I have an array of type Object in which I am saving object of
Share
Downcasting is to be done as follows:
Thus, in your particular case you probably want to do this:
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 encapsulatedPrintWriterfield. E.g.This way you can collect them in a
List<MyBean>(to learn more about collections, check this Sun tutorial on the subject).so that you can retrieve them as follows: