Serialization problem: java.lang.ClassCastException: java.lang.String can not be cast to java.util.ArrayList

0

I have the following code in which I need to return an object that serializes previously but it still gives me error at the time of casting even when my ArrayList is of Invoice type

   public void obtenerF() {

        try {
            ObjectInputStream entrada = new ObjectInputStream(new 
            FileInputStream("Factura.obj"));
            facturas = (ArrayList<Factura>) entrada.readObject();
            entrada.close();
    } catch (Exception ex) {
        Logger.getLogger(MnuPrincipal.class.getName()).log(Level.SEVERE, null, ex);
    }

}
    
asked by Angel Bulnes 25.04.2017 в 04:39
source

1 answer

1

Java exceptions do not lie to you. If they tell you that you received an object type String , an object type String was sent. You have to check the code that produces the source that you are reading later.

It is generally recommended to check the class of a deserialized object after readObject with if (objeto instanceof ...) . An cast without checking is almost never a good idea.

If you control the code for serialize, try a System.out.println(objeto.getClass().getName()); before saving / sending it. This way you realize where the problem is born.

    
answered by 25.04.2017 в 07:14