Перейти к содержимому

Classcastexception java что это

  • автор:

Class ClassCastException

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Classcastexception java что это

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Объяснение ClassCastException в Java

ClassCastException — это непроверенное исключение , которое сигнализирует о том, что код попытался привести ссылку к типу, подтипом которого он не является .

Давайте рассмотрим некоторые сценарии, которые приводят к возникновению этого исключения, и то, как мы можем их избежать.

2. Явный кастинг​

Для наших следующих экспериментов рассмотрим следующие классы:

2.1. Классы кастинга​

На сегодняшний день наиболее распространенным сценарием возникновения ClassCastException является явное приведение к несовместимому типу.

Например, давайте попробуем привести лягушку к млекопитающему :

Мы могли бы ожидать здесь ClassCastException , но на самом деле мы получаем ошибку компиляции: «несовместимые типы: лягушка не может быть преобразована в млекопитающее». Однако ситуация меняется, когда мы используем общий супертип:

Теперь мы получаем ClassCastException из второй строки:

Проверенное нисходящее приведение к Mammal несовместимо со ссылкой Frog, потому что Frog не является подтипом Mammal . В этом случае компилятор нам помочь не сможет, так как переменная Animal может содержать ссылку совместимого типа.

Интересно отметить, что ошибка компиляции возникает только тогда, когда мы пытаемся выполнить приведение к однозначно несовместимому классу. То же самое не верно для интерфейсов, потому что Java поддерживает множественное наследование интерфейсов, но только одиночное наследование для классов. Таким образом, компилятор не может определить, реализует ли ссылочный тип конкретный интерфейс или нет. Приведем пример:

Мы получаем ClassCastException во второй строке вместо ошибки компиляции:

2.2. Приведение массивов​

Мы видели, как классы обрабатывают приведение типов, теперь давайте посмотрим на массивы. Приведение массивов работает так же, как приведение классов. Однако нас может запутать автоупаковка и продвижение шрифта или их отсутствие.

Итак, давайте посмотрим, что происходит с примитивными массивами, когда мы пытаемся выполнить следующее приведение:

Вторая строка генерирует исключение ClassCastException , так как автоупаковка не работает для массивов.

Как насчет продвижения типа? Давайте попробуем следующее:

Мы также получаем ClassCastException , потому что повышение типа не работает для целых массивов.

2.3. Безопасный кастинг​

В случае явного приведения настоятельно рекомендуется проверить совместимость типов перед попыткой приведения с использованием instanceof .

Давайте посмотрим на пример безопасного приведения:

3. Загрязнение кучи​

В соответствии со спецификацией Java : « Загрязнение кучи может произойти только в том случае, если программа выполнила какую-либо операцию с необработанным типом, которая привела бы к непроверенному предупреждению во время компиляции».

Для нашего эксперимента рассмотрим следующий универсальный класс:

Теперь попробуем загрязнить кучу следующим образом:

Последняя строка вызовет исключение ClassCastException , поскольку она не может преобразовать двойную ссылку в Long .

4. Общие типы​

При использовании дженериков в Java мы должны опасаться стирания типов , что также может привести к ClassCastException в некоторых условиях.

Рассмотрим следующий общий метод:

А теперь назовем это:

На первый взгляд, мы можем разумно ожидать, что из блока catch будет возвращена нулевая ссылка. Однако во время выполнения из-за стирания типа параметр приводится к Object вместо String . Таким образом, перед компилятором стоит задача присвоить Integer String , что вызовет исключение ClassCastException.

5. Вывод​

В этой статье мы рассмотрели ряд распространенных сценариев неуместного кастинга.

Неявное или явное приведение ссылок Java к другому типу может привести к ClassCastException , если только целевой тип не является тем же или потомком фактического типа .

Explanation of ClassCastException in Java

Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.

Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.

The feedback is available from the minute you are writing it.

Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.

Of course, Digma is free for developers.

An interesting read.

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

ClassCastException is an unchecked exception that signals the code has attempted to cast a reference to a type of which it’s not a subtype.

Let’s look at some scenarios that lead to this exception being thrown and how we can avoid them.

2. Explicit Casting

For our next experiments, let’s consider the following classes:

2.1. Casting Classes

By far, the most common scenario for encountering a ClassCastException is explicitly casting to an incompatible type.

For example, let’s try to cast a Frog to a Mammal:

We might expect a ClassCastException here, but in fact, we get a compilation error: “incompatible types: Frog cannot be converted to Mammal”. However, the situation changes when we use the common super-type:

Now, we get a ClassCastException from the second line:

A checked downcast to Mammal is incompatible from a Frog reference because Frog is not a subtype of Mammal. In this case, the compiler cannot help us, as the Animal variable may hold a reference of a compatible type.

It’s interesting to note that the compilation error only occurs when we attempt to cast to an unequivocally incompatible class. The same is not true for interfaces because Java supports multiple interface inheritance, but only single inheritance for classes. Thus, the compiler can’t determine if the reference type implements a specific interface or not. Let’s exemplify:

We get a ClassCastException on the second line instead of a compilation error:

2.2. Casting Arrays

We’ve seen how classes handle casting, now let’s look at arrays. Array casting works the same as class casting. However, we might get confused by autoboxing and type-promotion, or lack thereof.

Thus, let’s see what happens for primitive arrays when we attempt the following cast:

The second line throws a ClassCastException as autoboxing doesn’t work for arrays.

How about type promotion? Let’s try the following:

We also get a ClassCastException because the type promotion doesn’t work for entire arrays.

2.3. Safe Casting

In the case of explicit casting, it is highly recommended to check the compatibility of the types before attempting to cast using instanceof.

Let’s look at a safe cast example:

3. Heap Pollution

As per the Java Specification: “Heap pollution can only occur if the program performed some operation involving a raw type that would give rise to a compile-time unchecked warning”.

For our experiment, let’s consider the following generic class:

We will now attempt to pollute the heap as follows:

The last line will throw a ClassCastException as it cannot transform a Double reference to Long.

4. Generic Types

When using generics in Java, we must be wary of type erasure, which can lead to ClassCastException as well in some conditions.

Let’s consider the following generic method:

And now let’s call it:

At first look, we can reasonably expect a null reference returned from the catch block. However, at runtime, due to type erasure, the parameter is cast to Object instead of String. Thus the compiler is faced with the task of assigning an Integer to String, which throws ClassCastException.

5. Conclusion

In this article, we have looked at a series of common scenarios for inappropriate casting.

Whether implicit or explicit, casting Java references to another type can lead to ClassCastException unless the target type is the same or a descendent of the actual type.

The code used in this article can be found over on GitHub.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *