Java中ClassCastException的解释

发布于 2024-07-23 05:41:55 字数 74 浏览 3 评论 0原文

我读了一些关于“ClassCastException”的文章,但我不太清楚它的含义。 什么是 ClassCastException?

I read some articles written on "ClassCastException", but I couldn't get a good idea on what it means. What is a ClassCastException?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

素手挽清风 2024-07-30 05:41:55

直接来自 ClassCastException 的 API 规范

抛出该异常表示代码已
试图将一个对象转换为
它不是其子类
实例。

因此,例如,当尝试将 Integer 转换为 String 时,String 不是 Integer 的子类>,因此将抛出ClassCastException

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

Straight from the API Specifications for the ClassCastException:

Thrown to indicate that the code has
attempted to cast an object to a
subclass of which it is not an
instance.

So, for example, when one tries to cast an Integer to a String, String is not an subclass of Integer, so a ClassCastException will be thrown.

Object i = Integer.valueOf(42);
String s = (String)i;            // ClassCastException thrown here.
小耗子 2024-07-30 05:41:55

这真的非常简单:如果您尝试将 A 类的对象类型转换为 B 类的对象,并且它们不兼容,则会出现类转换异常。

让我们考虑一下类的集合。

class A {...}
class B extends A {...}
class C extends A {...}
  1. 您可以将这些内容中的任何一个强制转换为 Object,因为所有 Java 类都继承自 Object。
  2. 您可以将 B 或 C 转换为 A,因为它们都是 A 的“种类”
  3. 。仅当真实对象是 B 时,您才可以将对 A 对象的引用转换为 B。
  4. 您可以'即使他们都是 A,也不要将 B 投射到 C。

It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.

Let's think of a collection of classes.

class A {...}
class B extends A {...}
class C extends A {...}
  1. You can cast any of these things to Object, because all Java classes inherit from Object.
  2. You can cast either B or C to A, because they're both "kinds of" A
  3. You can cast a reference to an A object to B only if the real object is a B.
  4. You can't cast a B to a C even though they're both A's.
染年凉城似染瑾 2024-07-30 05:41:55

如果您尝试向下转换一个类,但实际上该类不是该类型,则会发生异常。

考虑这个层次结构:

对象 -> 动物-> 狗

您可能有一个名为:

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

如果使用以下代码调用:

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

它将编译得很好,但在运行时您将得到一个 ClassCastException 因为 o 实际上是一个 Animal,而不是 Dog。

在 Java 的更高版本中,您确实会收到编译器警告,除非您这样做:

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

It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.

Consider this heirarchy:

Object -> Animal -> Dog

You might have a method called:

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

If called with this code:

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

It will compile just fine, but at runtime you will get a ClassCastException because o was in fact an Animal, not a Dog.

In later versions of Java you do get a compiler warning unless you do:

 Dog d;
 if(o instanceof Dog) {
     d = (Dog) o;
 } else {
     //what you need to do if not
 }
风筝有风,海豚有海 2024-07-30 05:41:55

考虑一个示例,

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:

  1. 尝试将一个类的对象转换为另一个类时要小心。 确保新类型属于其父类之一。
  2. 您可以使用泛型来防止 ClassCastException,因为泛型提供编译时检查并可用于开发类型安全的应用程序。

注释来源和其余的

Consider an example,

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

At Another t5 = (Another) new Goat(): you will get a ClassCastException because you cannot create an instance of the Another class using Goat.

Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.

How to deal with the ClassCastException:

  1. Be careful when trying to cast an object of a class into another class. Ensure that the new type belongs to one of its parent classes.
  2. You can prevent the ClassCastException by using Generics, because Generics provide compile time checks and can be used to develop type-safe applications.

Source of the Note and the Rest

画▽骨i 2024-07-30 05:41:55

你了解铸造的概念吗? 类型转换是类型转换的过程,这在 Java 中非常常见,因为它是一种静态类型语言。 一些示例:

通过 Integer.parseInt("1") 将字符串 "1" 转换为 int -> 没问题

将字符串 "abc" 转换为 int -> 引发 ClassCastException

或者想象一个包含 Animal.classDog.classCat.class 的类图

Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.

Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:

Cast the String "1" to an int, via Integer.parseInt("1") -> no problem

Cast the String "abc" to an int -> raises a ClassCastException

Or think of a class diagram with Animal.class, Dog.class and Cat.class

Animal a = new Dog();
Dog d = (Dog) a; // No problem, the type animal can be casted to a dog, because it's a dog.
Cat c = (Dog) a; // Will cause a compiler error for type mismatch; you can't cast a dog to a cat.
沐歌 2024-07-30 05:41:55

当您尝试将一种数据类型的对象转换为另一种数据类型时,Java 会引发类转换异常。

Java 允许我们将一种类型的变量转换为另一种类型,只要转换发生在兼容的数据类型之间。

例如,您可以将字符串转换为对象,类似地,包含字符串值的对象可以转换为字符串。

示例

假设我们有一个 HashMap,其中包含许多 ArrayList 对象。

如果我们编写这样的代码:

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

它会抛出类转换异常,因为哈希映射的 get 方法返回的值将是一个数组列表,但我们试图将其转换为字符串。 这会导致异常。

A class cast exception is thrown by Java when you try to cast an Object of one data type to another.

Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.

For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.

Example

Let us assume we have an HashMap that holds a number of ArrayList objects.

If we write code like this:

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

it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.

美人骨 2024-07-30 05:41:55

您试图将对象视为类的实例,但它不是。 这大致类似于尝试按下吉他上的制音踏板(钢琴有制音踏板,吉他没有)。

You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).

简美 2024-07-30 05:41:55

我可以为您提供 Java 中的 classcastException 的一个很好的例子,即使用“Collection”时,

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

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

上面的代码将在运行时为您提供 ClassCastException。 因为您试图将 Integer 转换为 String,所以会引发异常。

A very good example that I can give you for classcastException in Java is while using "Collection"

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

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

This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.

北恋 2024-07-30 05:41:55

一旦您认识到 JVM 无法猜测未知数,您就可以更好地理解 ClassCastException 和转换。 如果 B 是 A 的实例,则它在堆上拥有比 A 更多的类成员和方法。由于映射目标较大,JVM 无法猜测如何将 A 转换为 B,并且 JVM 将不知道如何填充额外的成员。

但如果 A 是 B 的实例,则这是可能的,因为 A 是对 B 的完整实例的引用,因此映射将是一对一的。

You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.

But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.

待天淡蓝洁白时 2024-07-30 05:41:55

Exception 不是 RuntimeException 的子类 -> 类转换异常

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

Exception is not a subclass of RuntimeException -> ClassCastException

    final Object  exception = new Exception();
    final Exception data = (RuntimeException)exception ;
    System.out.println(data);
情绪操控生活 2024-07-30 05:41:55

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)

这里抛出异常的原因是,当我创建列表对象时,我存储在列表中的对象是字符串“one” ,”但后来当我尝试取出这个对象时,我故意犯了一个错误,试图将其转换为整数。 因为 String 不能直接转换为 Integer(Integer 不是 String 的类型),所以会引发 ClassCastException。

A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.

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

If you try to run this Java program you’ll see that it will throw the following ClassCastException:

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

The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.

冰葑 2024-07-30 05:41:55

如果你想对对象进行排序,但类没有实现 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.Comparable

If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException
For example

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

Above main method will throw below runtime class cast exception

Exception in thread "main" java.lang.ClassCastException: com.default.Animal cannot be cast to java.lang.Comparable

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文