¿Cómo arreglar java.lang.classcastexception en Java?

ClassCastException en Java ocurre cuando intentamos convertir el tipo de datos de entrada en otro. Esto está relacionado con la función de conversión de tipos y la conversión de tipos de datos solo es correcta cuando una clase amplía una clase principal y la clase secundaria se convierte en su clase principal. 

Aquí podemos considerar la clase principal como un vehículo y la clase secundaria puede ser un automóvil, una bicicleta, un ciclo, etc. La clase principal como forma y la clase secundaria pueden ser formas 2d o formas 3d, etc.

Dos tipos diferentes de constructores disponibles para ClassCastException.

  1. ClassCastException(): Se utiliza para crear una instancia de la clase ClassCastException.
  2. ClassCastException(String s): se utiliza para crear una instancia de la clase ClassCastException, aceptando la string especificada como un mensaje.

Veamos en detalle

Java

import java.math.BigDecimal;
public class ClassCastExceptionExample {
    public static void main(String[] args)
    {
        // Creating a BigDecimal object
        Object sampleObject = new BigDecimal(10000000.45);
        System.out.println(sampleObject);
    }
}
Producción

10000000.4499999992549419403076171875

Si tratamos de imprimir este valor convirtiéndolo en un tipo de datos diferente como String o Integer, etc., obtendremos ClassCastException. 

Java

import java.math.BigDecimal;
public class Main {
    public static void main(String[] args)
    {
        // Creating a BigDecimal object
        Object sampleObject = new BigDecimal(10000000.45);
        
        // Trying to display the object by casting to String
        // As the object is created as BigDecimal but tried
        // to display by casting to String,
        // ClassCastException is thrown
        System.out.println((String)sampleObject);
    }
}

Producción :

Excepción en el subproceso «principal» java.lang.ClassCastException: la clase java.math.BigDecimal no se puede convertir a la clase java.lang.String (java.math.BigDecimal y java.lang.String están en el módulo java.base del cargador ‘bootstrap ‘)

en Principal.principal(Principal.java:11)

Podemos corregir la impresión de excepción mediante la conversión del código en el siguiente formato:

Java

import java.math.BigDecimal;
  
public class ClassCastExceptionExample {
    public static void main(String[] args)
    {
        // Creating a BigDecimal object
        Object sampleObject = new BigDecimal(10000000.45);
        
        // We can avoid ClassCastException by this way
        System.out.println(String.valueOf(sampleObject));
    }
}
Producción

10000000.4499999992549419403076171875

Por lo tanto, en cualquier caso, cuando tratamos de convertir el tipo de datos de un objeto, no podemos convertir directamente hacia abajo o hacia arriba a un tipo de datos específico. La transmisión directa no funcionará y arroja ClassCastException. En cambio, podemos usar

Método String.valueOf(). Convierte diferentes tipos de valores como int, long, boolean, character, float, etc., en la string. 

  1. public static String valueOf(boolean boolValue)
  2. public static String valueOf(char charValue)
  3. public static String valueOf(char[] charArrayValue)
  4. public static String valueOf(int intValue)
  5. public static String valueOf(long longValue)
  6. public static String valueOf(float floatValue)
  7. public static String valueOf(doble doubleValue)
  8. public static String valueOf(Object objectValue)

son los diferentes métodos disponibles y en nuestro ejemplo anterior, se utiliza el último método.

Entre la clase Padre e Hijo. El ejemplo muestra que la instancia de la clase principal no se puede convertir en una instancia de la clase secundaria.

Java

class Vehicle {
    public Vehicle()
    {
        System.out.println(
            "An example instance of the Vehicle class to proceed for showing ClassCastException");
    }
}
  
final class Bike extends Vehicle {
    public Bike()
    {
        super();
        System.out.println(
            "An example instance of the Bike class that extends Vehicle as parent class to proceed for showing ClassCastException");
    }
}
  
public class ClassCastExceptionExample {
    public static void main(String[] args)
    {
        Vehicle vehicle = new Vehicle();
        Bike bike = new Bike();
        Bike bike1 = new Vehicle();
        // Check out for this statement.  Tried to convert
        // parent(vehicle) object to child object(bike).
        // Here compiler error is thrown
  
        bike = vehicle;
    }
}

Error del compilador:

Compile time error occurrence when tried to convert parent object to child object

Para superar los errores de tiempo de compilación , necesitamos hacer downcast explícitamente. es decir, downcasting significa el encasillamiento de un objeto padre a un objeto hijo. Eso significa que las características del objeto principal se perdieron y, por lo tanto, no es posible una reducción implícita y, por lo tanto, debemos hacerlo explícitamente de la siguiente manera

Dando el snippet donde requiere el cambio. en el downcasting manera explícita

Java

// An easier way to understand Downcasting
class Vehicle {
    String vehicleName;
  
    // Method in parent class
    void displayData()
    {
        System.out.println("From Vehicle class");
    }
}
  
class Bike extends Vehicle {
    double cost;
  
    // Overriding the parent class method and we can
    // additionaly mention about the child class
    @Override void displayData()
    {
        System.out.println("From bike  class" + cost);
    }
}
  
public class ClassCastExceptionExample {
    public static void main(String[] args)
    {
  
        Vehicle vehicle = new Bike();
        vehicle.vehicleName = "BMW";
  
        // Downcasting Explicitly
        Bike bike = (Bike)vehicle;
  
        bike.cost = 1000000;
        
        // Though vehiclename is not assigned, it takes BMW
        // as it is
        System.out.println(bike.vehicleName);
        System.out.println(bike.cost);
        bike.displayData();
    }
}
Producción

BMW
1000000.0
From bike  class1000000.0

Upcasting de manera implícita

Un ejemplo de conversión ascendente del objeto secundario al objeto principal. Se puede hacer implícitamente. Esta instalación nos brinda la flexibilidad de acceder a los miembros de la clase principal.

Java

// An easier way to understand Upcasting
class Vehicle {
    String vehicleName;
    
    // Method in parent class
    void displayData()
    {
        System.out.println("From Vehicle class");
    }
}
class Bike extends Vehicle {
    
    double cost;
    
    // Overriding the parent class method and we can
    // additionaly mention about the child class
    @Override void displayData()
    {
        System.out.println("From bike  class..." + cost);
    }
}
  
public class ClassCastExceptionExample {
    public static void main(String[] args)
    {
        // Upcasting
        Vehicle vehicle = new Bike();
        
        vehicle.vehicleName = "Harley-Davidson";
        
        // vehicle.cost //not available as upcasting done
        // but originally Vehicle class dont have cost
        // attribute
        System.out.println(vehicle.vehicleName);
        
        vehicle.displayData(); // Hence here we will get
                               // output as 0.0
    }
}
Producción

Harley-Davidson
From bike  class...0.0

Arreglando ClassCastException de forma upcasting y al mismo tiempo, también se produce pérdida de datos

Java

class Vehicle {
    public Vehicle()
    {
        System.out.println(
            "An example instance of the Vehicle class to proceed for showing ClassCast Exception");
    }
    public String display()
    {
        return "Vehicle class display method";
    }
}
  
class Bike extends Vehicle {
    public Bike()
    {
        super(); // Vehicle class constructor msg display as
                 // super() is nothing but calling parent
                 // method
        System.out.println(
            "An example instance of the Bike class that extends \nVehicle as parent class to proceed for showing ClassCast Exception");
    }
    public String display()
    {
        return "Bike class display method";
    }
}
  
public class ClassCastExceptionExample {
    public static void main(String[] args)
    {
        Vehicle vehicle = new Vehicle();
        
        Bike bike = new Bike();
        
        // But we can make bike point to vehicle, i.e.
        // pointing child object to parent object This is an
        // example for upcasting of child object to parent
        // object. It can be done implicitly This facility
        // gives us the flexibility to access the parent
        // class members
        vehicle = bike;
        
        // As upcasted here, vehicle.display() will provide
        // "Bike class display method" as output It has lost
        // its parent properties as now vehicle is nothing
        // but bike only
        System.out.println(
            "After upcasting bike(child) to vehicle(parent).."
            + vehicle.display());
    }
}
Producción

An example instance of the Vehicle class to proceed for showing ClassCast Exception
An example instance of the Vehicle class to proceed for showing ClassCast Exception
An example instance of the Bike class that extends 
Vehicle as parent class to proceed for showing ClassCast Exception
After upcasting bike(child) to vehicle(parent)..Bike class display method

Conclusión: Por medio de upcasting o downcasting, podemos superar ClassCastException si estamos siguiendo las relaciones padre-hijo. Los métodos String.valueOf() ayudan a convertir los diferentes tipos de datos a String y de esa manera también podemos superar.

Publicación traducida automáticamente

Artículo escrito por priyarajtt y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *