Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java casting an Object as a PrintWriter

Tags:

java

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.

like image 834
n0ob Avatar asked Dec 21 '25 04:12

n0ob


1 Answers

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();
    // ...
}
like image 163
BalusC Avatar answered Dec 22 '25 19:12

BalusC