java中classcastexception的casting解释

bfhwhh0e  于 2021-07-12  发布在  Java
关注(0)|答案(12)|浏览(271)

我读了一些关于“classcastexception”的文章,但我对它的含义没有一个很好的理解。什么是classcastexception?

zynd9foi

zynd9foi1#

直接从api规范 ClassCastException :
抛出以指示代码试图将对象强制转换为其不是示例的子类。
例如,当一个人试图 IntegerString , String 不是的子类 Integer ,所以 ClassCastException 将被抛出。

Object i = Integer.valueOf(42);
String s = (String)i;            // ClassCastException thrown here.
h6my8fg2

h6my8fg22#

这非常简单:如果您试图将类a的对象类型转换为类b的对象,但它们不兼容,则会出现类转换异常。
让我们考虑一组类。

class A {...}
class B extends A {...}
class C extends A {...}

您可以将这些东西中的任何一个强制转换为object,因为所有java类都继承自object。
你可以将b或c转换成a,因为它们都是a的“种类”
只有当真实对象是b时,才能将a对象的引用强制转换为b。
即使他们都是a,你也不能把b换成c。

vtwuwzda

vtwuwzda3#

如果您试图向下转换一个类,但实际上该类不是那种类型,则会发生这种异常。
考虑一下这个继承权:
对象->动物->狗
您可能有一个名为:

public void manipulate(Object o) {
     Dog d = (Dog) o;
 }

如果使用此代码调用:

Animal a = new Animal();
 manipulate(a);

它可以很好地编译,但是在运行时您会得到一个 ClassCastException 因为o实际上是一种动物,而不是狗。
在更高版本的java中,确实会收到编译器警告,除非:

Dog d;
 if(o instanceof Dog) {
     d = (Dog) o;
 } else {
     //what you need to do if not
 }
9avjhtql

9avjhtql4#

举个例子,

class Animal {
    public void eat(String str) {
        System.out.println("Eating for grass");
    }
}

class Goat extends Animal {
    public void eat(String str) {
        System.out.println("blank");
    }
}

class Another extends Goat{
  public void eat(String str) {
        System.out.println("another");
  }
}

public class InheritanceSample {
    public static void main(String[] args) {
        Animal a = new Animal();
        Another t5 = (Another) new Goat();
    }
}

Another t5 = (Another) new Goat() :您将获得 ClassCastException 因为无法创建 Another 类使用 Goat .
注意:转换仅在类扩展父类并且子类被强制转换为其父类的情况下有效。
如何处理这个问题 ClassCastException :
在试图将一个类的对象强制转换为另一个类时要小心。确保新类型属于其父类之一。
您可以通过使用泛型来防止classcastexception,因为泛型提供编译时检查,并且可以用于开发类型安全的应用程序。
笔记的来源和其他

xxe27gdn

xxe27gdn5#

当您尝试将一种数据类型的对象强制转换为另一种数据类型时,java会引发类强制转换异常。
java允许我们将一种类型的变量转换为另一种类型,只要转换发生在兼容的数据类型之间。
例如,可以将字符串转换为对象,类似地,可以将包含字符串值的对象转换为字符串。

示例

假设我们有一个hashmap,其中包含许多arraylist对象。
如果我们这样写代码:

String obj = (String) hmp.get(key);

它将抛出类强制转换异常,因为哈希Map的get方法返回的值将是数组列表,但我们正在尝试将其强制转换为字符串。这将导致异常。

nzk0hqpo

nzk0hqpo6#

你了解铸造的概念吗?casting是类型转换的过程,在java中非常常见,因为它是一种静态类型语言。一些例子:
把字符串“1”转换成int->没问题
将字符串“”转换为int->引发classcastexception
或者考虑一个包含animal.class、dog.class和cat.class的类图

Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because its a dog.
Cat c = (Dog) a; // Raises class cast exception; you can't cast a dog to a cat.
b4qexyjb

b4qexyjb7#

您正试图将一个对象视为它不是的类的示例。这大致类似于试图按下吉他上的阻尼踏板(钢琴有阻尼踏板,吉他没有)。

kadbb459

kadbb4598#

对于java中的classcastexception,我可以给您一个非常好的例子,就是在使用“collection”时

List list = new ArrayList();
list.add("Java");
list.add(new Integer(5));

for(Object obj:list) {
    String str = (String)obj;
}

上面的代码将在运行时为您提供classcastexception。因为您正试图将整数转换为字符串,这将引发异常。

klh5stk1

klh5stk19#

一旦认识到jvm无法猜出未知值,就可以更好地理解classcastexception和casting。如果b是a的示例,则堆上的类成员和方法比a多。jvm无法猜测如何将a转换为b,因为Map目标更大,jvm将不知道如何填充额外的成员。
但是如果a是b的一个示例,这是可能的,因为a是对b的一个完整示例的引用,所以Map将是一对一的。

ocebsuys

ocebsuys10#

java classcastexception是当您试图将一个类从一种类型不正确地转换为另一种类型时可能发生的异常。

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ClassCastExceptionExample {

  public ClassCastExceptionExample() {

    List list = new ArrayList();
    list.add("one");
    list.add("two");
    Iterator it = list.iterator();
    while (it.hasNext()) {
        // intentionally throw a ClassCastException by trying to cast a String to an
        // Integer (technically this is casting an Object to an Integer, where the Object 
        // is really a reference to a String:
        Integer i = (Integer)it.next();
    }
  }
 public static void main(String[] args) {
  new ClassCastExceptionExample();
 }
}

如果您尝试运行此java程序,您将看到它将抛出以下classcastexception:

Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample  (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main  (ClassCastExceptionExample.java:19)

这里抛出异常的原因是,当我创建list对象时,我存储在list中的对象是字符串“one”,但后来当我试图取出这个对象时,我故意犯了一个错误,试图将其转换为整数。由于字符串不能直接转换为整数-整数不是字符串类型-因此会引发classcastexception。

t1qtbnec

t1qtbnec11#

如果您想对对象进行排序,但类没有实现comparable或comparator,那么您将得到classcastexception示例

class Animal{
   int age;
   String type;

   public Animal(int age, String type){
      this.age = age;
      this.type = type;
   }
}
public class MainCls{
   public static void main(String[] args){
       Animal[] arr = {new Animal(2, "Her"), new Animal(3,"Car")};
       Arrays.sort(arr);
   }
}

上面的main方法将抛出下面的运行时类强制转换异常
线程“main”java.lang.classcastexception中的异常:com.default.animal无法转换为java.lang.com

zd287kbt

zd287kbt12#

exception不是runtimeexception->classcastexception的子类

final Object  exception = new Exception();
    final Exception data = (RuntimeException)exception ;
    System.out.println(data);

相关问题