Java object casting as PrintWriter

I have an array of type Objectin which I store an object of different types, I want to drop them back after they are selected from the array. So when I take the PrintWriter object, I try PrintWriter(objArray[1][2]), but it will not work, how can I do it.

+3
source share
1 answer

Downcasting should be done as follows:

SubType instanceOfSubType = (SubType) instanceOfSuperType;

So in your particular case, you probably want to do this:

PrintWriter printWriter = (PrintWriter) objArray[1][2];

Also see the "Cast Objects" chapter in the Sun Inheritance Tutorial (scroll about half).

, Object[] . , Javabean- PrintWriter. .

public class MyBean {
    private PrintWriter printWriter;
    public void setPrintWriter(PrintWriter printWriter) {
        this.printWriter = printWriter;
    }
    public PrintWriter getPrintWriter() {
        return printWriter;
    }
}

List<MyBean> ( , Sun ).

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);
// ...

:

for (MyBean myBean : myBeans) {
    PrintWriter printWriter = myBean.getPrintWriter();
    // ...
}
+3

Source: https://habr.com/ru/post/1732900/


All Articles