📌  相关文章
📜  如何在Java修复Java .lang.classcastexception ?

📅  最后修改于: 2022-05-13 01:55:10.289000             🧑  作者: Mango

如何在Java修复Java .lang.classcastexception ?

Java的ClassCastException 当我们尝试将条目的数据类型转换为另一种时会发生。这与类型转换功能有关,只有在类扩展父类并将子类强制转换为其父类时,数据类型转换才能成功。

这里我们可以将父类视为车辆,子类可以是汽车、自行车、自行车等,父类可以是形状,子类可以是 2d 形状或 3d 形状等。

可用于 ClassCastException 的两种不同类型的构造函数。

  1. ClassCastException():用于创建 ClassCastException 类的实例。
  2. ClassCastException(String s):它用于通过接受指定的字符串作为消息来创建 ClassCastException 类的实例。

让我们详细看看

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);
    }
}


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);
    }
}


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));
    }
}


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;
    }
}


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();
    }
}


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
    }
}


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());
    }
}


输出

10000000.4499999992549419403076171875

如果我们尝试通过转换为不同的数据类型(如 String 或 Integer 等)来打印此值,我们将收到 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);
    }
}

输出 :

我们可以通过转换以下格式的代码来修复异常打印:

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));
    }
}
输出
10000000.4499999992549419403076171875

因此,在任何情况下,当我们尝试转换对象的数据类型时,我们都不能直接向下或向上转换为指定的数据类型。直接转换将不起作用,它会抛出 ClassCastException。相反,我们可以使用

String.valueOf() 方法。它将不同类型的值(如 int、long、boolean、 字符、float 等)转换为字符串。



  1. 公共静态字符串 valueOf(boolean boolValue)
  2. 公共静态字符串 valueOf(char charValue)
  3. public static String valueOf(char[] charArrayValue)
  4. 公共静态字符串 valueOf(int intValue)
  5. 公共静态字符串 valueOf(long longValue)
  6. 公共静态字符串 valueOf(float floatValue)
  7. 公共静态字符串 valueOf(double doubleValue)
  8. public static String valueOf(Object objectValue)

是可用的不同方法,在我们上面的示例中,使用了最后一种方法。

在父类和子类之间。示例显示无法将父类的实例强制转换为子类的实例。

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;
    }
}

编译器错误:

尝试将父对象转换为子对象时发生编译时错误

为了克服编译时错误,我们需要明确地向下转型。即向下转换意味着将父对象类型转换为子对象。这意味着父对象的特征丢失,因此没有可能的隐式向下转换,因此我们需要按照以下方式明确地做

在需要更改的地方提供代码片段。以向下的显式方式

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();
    }
}
输出
BMW
1000000.0
From bike  class1000000.0

向上转换隐式方式

将子对象向上转换为父对象的示例。它可以隐式完成。这种便利使我们可以灵活地访问父类成员。

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
    }
}
输出
Harley-Davidson
From bike  class...0.0

以向上转换的方式修复ClassCastException,同时也会发生数据丢失

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());
    }
}
输出
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

结论:通过向上或向下转换,如果我们遵循父子关系,我们可以克服 ClassCastException。 String.valueOf() 方法有助于将不同的数据类型转换为 String,这样我们也可以克服。