I have a conceptual problem about this error: Exception in thread "main" java.lang.ClassCastException: java.lang.String can not be cast

0

Good afternoon, in a code that I am elaborating in an empirical way I find a conceptual failure on my part and I do not know how to solve it, the error is as follows:

  

Exception in thread "main" java.lang.ClassCastException: java.lang.String can not be cast to prodemios.proceso at prodemios.PrincipalES.main (PrincipalES.java:32

My code is as follows:

package prodemios;

import java.util.*;

public class PrincipalES {
    static String contraseña;
    static String usuario;
    static int validacion;
    static int puntosg;
    static int puntosf;
    static boolean encendido=true;

    public static void main (String[] args) {
        Scanner leer=new Scanner(System.in);

        System.out.println("Si es usuario oprima 1, si es servidor oprima 2");
        validacion=leer.nextInt();

        switch(validacion){
        case 1:
            usuario();
            break;
        case 2:
            validar();
            break;
        }

        proceso user;
        serializador s = new serializador();
        user=(proceso)s.cargarObjeto("prodemios.dat");
        System.out.println(user.getNombre());
        System.out.println(user.getPuntos());
        //guardaD.
    }

    public static void validar(){
        Scanner leer=new Scanner(System.in);
        BaseDatos BD=new BaseDatos();
        System.out.println("ingresa la contraseña");
        contraseña=leer.nextLine();
        if(contraseña.equals("prodemios")){
            BD.servidor();    
        }
        else{System.out.println("error en la contraseña");}
    }

    public static void usuario(){
        Scanner leer=new Scanner(System.in);
        usuario usu= new usuario();
        System.out.println("bienvenido al prode, oprime A si eres usuario nuevo\nO B si eres usuario antiguo");
        usuario=leer.nextLine();

        if(usuario.equals("a")){    
          usu.usuarionuevo();
        }

        if(usuario.equals("b")){
           usu.usuarioantiguo(); 
        }

        proceso user;
        serializador s = new serializador();
        user=(proceso)s.cargarObjeto("prodemios.dat");
        System.out.println(user.getNombre());
        System.out.println(user.getPuntos());
    }
}
package prodemios;

import java.util.*;

public class BaseDatos {
    private int usuariosPuntos;
    private String usuariosNombre="";
    private int i;
    private int cantidad;
    private int cont;

    public void servidor() {
        Scanner leer = new Scanner(System.in);

        System.out.println("ingresa cantidad de usuarios");
        cantidad=leer.nextInt();

        proceso datos[]=new proceso[cantidad];

        for(i=0;i<=datos.length-1;i++){
            cont=cont+1;
            System.out.println("ingresa el nombre del usuario numero "+cont);
            usuariosNombre=leer.next();

            datos[i]=new proceso(usuariosNombre, usuariosPuntos);
        }

        cont=0;
        for(i=0;i<=datos.length-1;i++){
            cont=cont+1;
            System.out.println("ingresa los puntos del usuario numero "+cont);
            usuariosPuntos=leer.nextInt();

            datos[i]=new proceso(usuariosNombre, usuariosPuntos);
        }
    }
}
package prodemios;

import java.util.Scanner;

public class usuario {
    private String nombre;
    private int puntosgeneral;
    private int puntosfecha;

    public void usuarionuevo(){
        Scanner leer=new Scanner(System.in);

        System.out.println("ingresa tu nombre");
        nombre=leer.next();

        System.out.println("ingresa tus puntos realizados");
        puntosgeneral=leer.nextInt();
        proceso pr = new proceso(nombre,puntosgeneral);
    }

    public void usuarioantiguo(){
        Scanner leer=new Scanner(System.in);

        System.out.println("ingresa tus puntos realizados en la fecha");
        puntosfecha=leer.nextInt();
        proceso pr = new proceso(null,puntosfecha);
    }

    public int getPuntosgeneral() {
        return puntosgeneral;
    }

    public void setPuntosgeneral(int puntosgeneral) {
        this.puntosgeneral = puntosgeneral;
    }

    public int getPuntosfecha() {
        return puntosfecha;
    }

    public void setPuntosfecha(int puntosfecha) {
        this.puntosfecha = puntosfecha;
    }
}
package prodemios;

public class proceso {
    private String nombre;
    private int puntos;

    public proceso(){       
        nombre="";
        puntos=0;
    }

    public proceso(String nom,int punt){
        nombre=nom;
        puntos=punt;
        serializador guardaD = new serializador();
        guardaD.guardaObjeto(getNombre(),getPuntos());  
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public int getPuntos() {
        return puntos;
    }

    public void setPuntos(int puntos) {
        this.puntos = puntos;
    }

    //usu.getPuntosgeneral();
    //usu.getPuntosfecha()
}
package prodemios;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class serializador {
    private ObjectInputStream cargarDato;
    private ObjectOutputStream guardarDato;

    public void guardaObjeto(Object nombre, Object puntos ){
        try {
            guardarDato= new ObjectOutputStream(new FileOutputStream("prodemios.dat"));
            guardarDato.writeObject(nombre);
            guardarDato.writeObject(puntos);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public Object cargarObjeto(String nombreArchivo){
        Object retorno = null;
        try {
            cargarDato= new ObjectInputStream(new FileInputStream(nombreArchivo));
            retorno=cargarDato.readObject();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return retorno;
    }
}

The class process is the one that receives the data from the BaseDato or user classes and builds the objects that go directly to the serializer, I would greatly appreciate the help, happy afternoon.

    
asked by pangloss 22.12.2017 в 23:47
source

3 answers

0

user = (process) s.loadObject ("prodemios.dat");

It is the error so that method returns a String and you try to convert it into "process". First of all according to what I understand that is not the proper way to store objects. To save an object, the first thing that you have to implement the class of the object that you are going to keep, is the Serializable class. I recommend this post link

    
answered by 23.12.2017 / 00:20
source
1

The problem you have is in the serializer class ( Serializer ), and in particular in the "loadObject" method, this method is returning an object that can not cast process ( > Process ).

When doing MyClass mobj = (MyClass)obj you are finding out which className is different and you can not do the casting.

  

Solution: By Interface, the easiest you create an interface with the method that you are going to execute by   example:

public interface InterfaceDTO{
    String getNombre();
}

public class Proceso implements InterfaceDTO{
 ..
 public String getNombre(){..}
}

And then you do the casting:

MyInterface mobj = (myInterface)obj;
mobj.doStuff();
  

Solution: By Reflection, something more complex conceptually.

MyClass mobj = MyClass.class.cast(obj);

Note: By definition and agreement the names of the classes are uppercase and following the rules of Cammell notation "PersonalizedClassEmployee".

    
answered by 23.12.2017 в 00:20
0

Your problem seems to be that the data you load is a String (the content of the prodemios.dat file is interpreted as a string of characters), but you are trying to interpret it as a "process" type. Are you sure you have previously deserialized it correctly in such a file?

    
answered by 23.12.2017 в 00:10