Classcastexception, literally, is a type conversion error, which is usually an error during forced type conversion. Next, analyze the causes of classcastexception, and provide a solution to this exception.
How does this exception occur? Let's give a more vivid example.
Animal indicates animals, dog indicates dogs, cat indicates cats, and animal subclasses. See the followingCode:
Animal a1 = new dog (); // 1
Animal a2 = new CAT (); // 2
Dog d1 = (DOG) A1; // 3
Dog D2 = (DOG) A2; // 4
The Code in line 2 is basically the same as that in line 2. It literally converts an animal (animal) to a dog, but the code in line 3 produces a java. Lang. classcastexception. The reason is that you want to convert a cat (A2 this animal is a cat) into a dog, and In line 2, it is to convert the dog into a dog, so you can.
From the above example, Java. lang. classcastexception is an exception generated during forced type conversion. Forced type conversion is performed only when the type of the object to which the parent class references is a subclass, if the type of the object referenced by the parent class is not a subclass, Java is generated. lang. classcastexception exception. Both A1 and A2 are animals, but A1 is a dog, while A2 is a cat. Therefore, A1 must be converted into a dog, because A1 is a dog and A2 is a cat, an error occurs when it is converted to a dog.
How can this problem be solved? If you know the specific type of the object to be accessed, convert it to this type. If the type cannot be determined, you can use the following two methods (assuming the object is O ):
1. Use O. getclass (). getname () to obtain the specific type. You can use the output statement to output this type and then perform specific processing based on the type.
2. The if (O instanceof type) statement is used to determine the type of O.